/*
 * DayFragment.java
 * Displays the activities of the day
 */

package com.cc.infosur.mytrip;

import android.content.res.Configuration;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.os.Bundle;
import android.os.ParcelFileDescriptor;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.cc.infosur.greendao.DaoMaster;
import com.cc.infosur.greendao.DaoMaster.DevOpenHelper;
import com.cc.infosur.greendao.DaoSession;
import com.cc.infosur.greendao.Day;
import com.cc.infosur.greendao.DayDao;
import com.cc.infosur.greendao.DayServiceRel;
import com.cc.infosur.greendao.DayServiceRelDao;
import com.cc.infosur.greendao.DayServiceRelDao.Properties;
import com.cc.infosur.greendao.Excursion;
import com.cc.infosur.greendao.Service;
import com.cc.infosur.greendao.ServiceDao;
import com.cc.infosur.greendao.Step;
import com.cc.infosur.greendao.Trip;
import com.cc.infosur.greendao.TripDao;
import com.cc.infosur.main.MainActivity;
import com.cc.infosur.main.Var;
import com.cc.infosur.map.MapFragment;

import org.osmdroid.views.MapView;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import com.cc.infosur.R;

public class DayFragment extends Fragment {

    // Buttons and textviews
    private static MapView map;

    private ImageView goToPrevDayButton;

    private ImageView mapButton;
    private ImageButton miniMapButton;

    private TextView txtDay;
    private TextView txtNameTrip;
    private TextView txtDateTrip;
    private LinearLayout dayServicesLayout;
    private LayoutInflater Vinflater;

    private int dayNo; // current day
    private int dayLimit; // last day
    private int totalDays;
    private String titleday;
    private List<Day> days;
    private Trip trip;
    public MainActivity mActivity;

    // Database variables
    private SQLiteDatabase db;
    private DevOpenHelper helper;
    private DaoSession daoSession;
    private DaoMaster daoMaster;
    private TripDao tripDao;
    private DayServiceRelDao dayServiceRelDao;
    private ServiceDao serviceDao;
    private DayDao dayDao;

    private int countDay = 1;



    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Reload current fragment
        final FragmentTransaction ft = getFragmentManager().beginTransaction();
        ft.detach(this);
        ft.attach(this);
        ft.commit();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {


        View V = inflater.inflate(R.layout.day, container, false);
        Vinflater = inflater;
        mActivity = (MainActivity) this.getActivity();

        // Get the buttons and textviews
        goToPrevDayButton = (ImageView) V.findViewById(R.id.goToPrevDayButton);
        goToPrevDayButton.setOnClickListener(prevDayListener);

        mapButton = (ImageView) V.findViewById(R.id.mapButton);
		mapButton.setOnClickListener(mapListener);

        txtDay = (TextView) V.findViewById(R.id.textDay);
        txtNameTrip = (TextView) V.findViewById(R.id.textNameTrip);

        dayServicesLayout = (LinearLayout) V.findViewById(R.id.dayServicesLayout);

        // Prepare db
        helper = new DevOpenHelper(getActivity(), "tripdb", null);
        db = helper.getWritableDatabase();
        daoMaster = new DaoMaster(db);
        daoSession = daoMaster.newSession();

        tripDao = daoSession.getTripDao();
        dayServiceRelDao = daoSession.getDayServiceRelDao();
        serviceDao = daoSession.getServiceDao();
        dayDao = daoSession.getDayDao();

        this.trip = tripDao.loadAll().get(0);

        // Display the trip's name
        txtDay.setText(trip.getName());

        // Display the trip's date
        SimpleDateFormat ffr = new SimpleDateFormat("dd MMMM yyyy", new Locale("fr"));
        txtNameTrip.setText(ffr.format(trip.getDateFrom()));

        days = trip.getDays();
        dayLimit = days.size() - 1;

        // Load all days
        totalDays = dayDao.loadAll().size();

        // Initialize Day
        initializeDay();

        return V;
    }

    //Map button action
    private OnClickListener mapListener = new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Var.step.clear();
            Var.step.addAll(trip.getSteps());
            Var.position = 0;
            MapFragment fg = new MapFragment();

            FragmentTransaction trans = getFragmentManager().beginTransaction();

            trans.replace(R.id.root_fragment, fg);

            trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            trans.addToBackStack(null);

            trans.commit();
        }
    };

    public class MyOnClickListener implements OnClickListener{
        int index;
        Step step;

        public MyOnClickListener(int index, Step step)
        {
            this.index = index;
            this.step = step;
        }

        @Override
        public void onClick(View arg0) {
            MapFragment mf = new MapFragment();

            FragmentTransaction trans = getFragmentManager().beginTransaction();

            trans.replace(R.id.root_fragment, mf);

            trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            trans.addToBackStack(null);

            trans.commit();

            Var.position = index+1;
            Var.step.clear();
            Var.step.add(this.step);
        }
    }

    //previous day listener and next day listener allows you to navigate through the days
    private OnClickListener prevDayListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            getFragmentManager().popBackStack();
        }
    };


    //service listener: shows the Service fragment with the service description when click on the service
    private OnClickListener serviceListener = new OnClickListener() {
        @Override
        public void onClick(View v) {
            ServiceFragment fg = new ServiceFragment();
            fg.setDayId(days.get(dayNo).getId());

            TextView tv = (TextView) v.findViewById(R.id.descriptionNoId);
            long i = Long.parseLong(tv.getText().toString());
            fg.setServiceId(i);
            fg.setDescriptionNo(0);

            FragmentTransaction trans = getFragmentManager().beginTransaction();

            trans.replace(R.id.root_fragment, fg);

            trans.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            trans.addToBackStack(null);

            trans.commit();
        }
    };

    public void setDayNo(int n) {
        this.dayNo = n;
    }

    public int getDayNo() {
        return this.dayNo;
    }

    private void initializeDay() {

        //Initialize the day with its services and alternative services
        SimpleDateFormat dateFormat = new SimpleDateFormat("EEEE, d MMMM");

        dayServicesLayout.removeAllViews();

        List<Step> steps = trip.getSteps();

        LinearLayout serviceLayout = null;
        LinearLayout layoutServices;
        LinearLayout serviceNameLayout;
        String currentRegion = "";

        for (int i = 0; i < steps.size(); i++) {
            List<Excursion> excursions = steps.get(i).getExcursions();

            for (int j = 0; j < excursions.size(); j++) {
                List<Service> services = excursions.get(j).getServices();

                for (int k = 0; k < services.size(); k++) {
                    Service service = services.get(k);
                    if(service.getType() != 2){

                        serviceLayout = (LinearLayout) Vinflater.inflate(R.layout.servicelayout, null);
                        LinearLayout linearDate = (LinearLayout) serviceLayout.findViewById(R.id.linearLayoutDate);
                        txtDateTrip = (TextView) serviceLayout.findViewById(R.id.textDateTrip);

                        miniMapButton = (ImageButton) linearDate.findViewById(R.id.miniMapButton);
                        ///miniMapButton.setOnClickListener(miniMapListener);

                        miniMapButton.setOnClickListener(new MyOnClickListener(k, steps.get(i)));

                        linearDate.setOnClickListener(new MyOnClickListener(k, steps.get(i)));

                        if (k == 1) {
                            txtDateTrip = (TextView) serviceLayout.findViewById(R.id.textDateTrip);
                            linearDate.setVisibility(View.VISIBLE);
                            txtDateTrip.setText(service.getLocality());
                        } else {
                            linearDate.setVisibility(View.GONE);
                        }

                        TextView tv = (TextView) serviceLayout.findViewById(R.id.serviceName);
                        tv.setText(service.getName());
                        tv = (TextView) serviceLayout.findViewById(R.id.serviceTime);

                        // StartHour - convert into String - remove whitespace
                        String startHour = service.getStartHour().toString().trim();
                        // If startHour is not empty
                        if(startHour.length() > 0) {
                            // If startHour different to 0-0
                            if (!(startHour.equals("0-0"))) {
                                // Split the string at "-"
                                String[] startHourSplit = startHour.split("-");
                                tv.setText(startHourSplit[0].substring(0, 2) + "h" + startHourSplit[0].substring(2, 5));
                                //System.out.println(startHourSplit[0].substring(0, 2) + "h" + startHourSplit[0].substring(2, 5));
                            }
                        }


                        tv = (TextView) serviceLayout.findViewById(R.id.descriptionNoId);
                        tv.setText(Long.toString(service.getId()));

                        if (service.getIcon() != null) {
                            Bitmap bmp = BitmapFactory.decodeByteArray(service.getIcon(), 0, service.getIcon().length);
                            ImageView iv = (ImageView) serviceLayout.findViewById(R.id.serviceImage);
                            iv.setImageBitmap(bmp);
                        }

                        if (!service.getName().equals("My own"))
                            serviceLayout.setOnClickListener(serviceListener);

                        dayServicesLayout.addView(serviceLayout);
                    }
                }
            }
        }
    }

}
