/*
 * 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.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.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.List;

import com.cc.infosur.R;

public class DayFragmentCopie 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;
    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();

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

        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.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;

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

        @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;
        }
    }

    //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();

        // DAYS
        for(int k = 0 ; k < totalDays ; k++) {
            List<DayServiceRel> servicesId = dayServiceRelDao.queryBuilder()
                    .where(Properties.Day.eq(days.get(k).getId()))
                    .orderAsc(Properties.Order).list();

            System.out.println( k + " :: $$ servicesId.size() $$ :: " + servicesId.size());

            // SERVICES PER DAY
            for (int i = 0; i < servicesId.size(); i++) {

                final Service service = serviceDao.load(servicesId.get(i).getService());

                // If the service is available
                if (service.getAvailable()) {
                        LinearLayout serviceLayout = (LinearLayout) Vinflater.inflate(R.layout.servicelayout, null);

                        LinearLayout linearDate = (LinearLayout) serviceLayout.findViewById(R.id.linearLayoutDate);


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

                        miniMapButton.setOnClickListener(new MyOnClickListener(k));


                        linearDate.setOnClickListener(new MyOnClickListener(k));


                        // Set margin TOP after the first one
                        if(k > 0) {
                            LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) linearDate.getLayoutParams();
                            params.setMargins(0,5,0,0);
                            linearDate.setLayoutParams(params);
                        }

                        // Display Day X + Date only once
                            if (i == 0) {
                                txtDateTrip = (TextView) serviceLayout.findViewById(R.id.textDateTrip);
                                linearDate.setVisibility(View.VISIBLE);
                                txtDateTrip.setText(service.getLocality());


                            } else {
                                linearDate.setVisibility(View.GONE);
                            }

                        System.out.println(" ** service.getType() ** " +  service.getType() );
                        if(service.getType() != null) {
                            if(service.getType() == 2) {
                                ImageView img = (ImageView) serviceLayout.findViewById(R.id.imageHotel);
                                img.setVisibility(View.VISIBLE);


                            }
                        }

                        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("-");
                                if (startHourSplit.length !=0) {
                                    if (startHourSplit[0].equals("0")) // FROM : empty
                                        tv.setText("\n" + startHourSplit[1]);
                                    else if (startHourSplit[1].equals("0")) // TO : empty
                                        tv.setText(startHourSplit[0]);
                                        // tv.setText(startHourSplit[0] + "\n");
                                    else // FROM & TO : NOT empty
                                        tv.setText(startHourSplit[0].substring(0,2)+ "h" + startHourSplit[0].substring(2,4)+ "\n" + startHourSplit[1].substring(0,2)+ "h" +startHourSplit[1].substring(2,4));
                                }else tv.setText("");
                            } else tv.setText("");
                        } else tv.setText("");


                        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);

                // __ END IF{ } SERVICE IS AVAILABLE
                } else {

                    LinearLayout serviceLayout = (LinearLayout) Vinflater.inflate(R.layout.servicelayout, null);


                    //When the service is unavailable shows the alternative activities
                    serviceLayout = (LinearLayout) Vinflater.inflate(R.layout.alternativeservices, null);
                    TextView tv = (TextView) serviceLayout
                            .findViewById(R.id.serviceName);
                    tv.setText(service.getName());
                    tv = (TextView) serviceLayout.findViewById(R.id.serviceTime);

                    //String[] startHour = service.getStartHour().split(" ");
                    //tv.setText(startHour[0] + " \n " + startHour[1]);
                    tv.setText(service.getStartHour());
                    Bitmap bmp = BitmapFactory.decodeByteArray(service.getIcon(),
                            0, service.getIcon().length);
                    ImageView iv = (ImageView) serviceLayout
                            .findViewById(R.id.serviceImage);
                    iv.setImageBitmap(bmp);

                    TextView t = (TextView) serviceLayout
                            .findViewById(R.id.dateTextView);
                    t.setText("Your alternative to " + service.getName());
                    LinearLayout ll = (LinearLayout) serviceLayout
                            .findViewById(R.id.alternativeactivitieslayout);
                    RadioGroup rbg = (RadioGroup) serviceLayout
                            .findViewById(R.id.radioGroup1);
                    LinearLayout tmp = (LinearLayout) serviceLayout
                            .findViewById(R.id.alternativeactivitiesspacelayout);
                    rbg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
                        public void onCheckedChanged(RadioGroup arg0, int id) {
                            for (int i = 0; i < arg0.getChildCount(); i++) {
                                RadioButton radioButton = (RadioButton) arg0
                                        .getChildAt(i);
                                Service service = serviceDao
                                        .load((long) radioButton.getId());
                                service.setActivated(false);
                                service.update();
                            }
                            Service acservice = serviceDao.load((long) id);
                            acservice.setActivated(true);
                            acservice.update();
                            MyTripFragment myTripFragment = (MyTripFragment) mActivity.mStacks.get("MYTRIP_TAB").firstElement();
                            myTripFragment.chooseAlternativeActivity(service.getId(), acservice.getId());
                            MapFragment mapFragment = (MapFragment) mActivity.mStacks.get("MAP_TAB").firstElement();
                            mapFragment.updateDayServices(getDayNo(), service.getId(), acservice.getId());
                        }
                    });
                    // List<RadioButton> radioButtonsList = new
                    // ArrayList<RadioButton>();
                    for (Service alternativeService : service.getAlternativeServices()) {
                        if (alternativeService.getAvailable()) {
                            RadioButton rb = new RadioButton(getActivity());
                            RadioGroup.LayoutParams params = new RadioGroup.LayoutParams(
                                    ViewGroup.LayoutParams.WRAP_CONTENT,
                                    ViewGroup.LayoutParams.MATCH_PARENT, 1);
                            params.gravity = Gravity.CENTER;
                            rb.setGravity(Gravity.CENTER);
                            rb.setBackgroundDrawable(getResources().getDrawable(
                                    R.drawable.service_layout_background));
                            rb.setLayoutParams(params);
                            rb.setChecked(alternativeService.getActivated());
                            rb.setId(alternativeService.getId().intValue());
                            rbg.addView(rb);

                            // to set the background on the right of the radio
                            // button
                            LinearLayout spaceLayout = new LinearLayout(
                                    getActivity());
                            spaceLayout.setBackgroundDrawable(getResources()
                                    .getDrawable(
                                            R.drawable.service_layout_background));
                            tmp.addView(spaceLayout, new LinearLayout.LayoutParams(
                                    ViewGroup.LayoutParams.MATCH_PARENT,
                                    ViewGroup.LayoutParams.MATCH_PARENT, 1));

                            LinearLayout alternativeLayout = (LinearLayout) Vinflater
                                    .inflate(R.layout.alternativeservicelayout,
                                            null);
                            tv = (TextView) alternativeLayout
                                    .findViewById(R.id.serviceName);
                            tv.setText(alternativeService.getName());
                            tv = (TextView) alternativeLayout
                                    .findViewById(R.id.descriptionNoId);
                            tv.setText(Long.toString(alternativeService.getId()));

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

                            alternativeLayout.setOnClickListener(serviceListener);
                            ll.addView(alternativeLayout);
                        }
                    }
                    dayServicesLayout.addView(serviceLayout);

                } // __ END IF{ } ELSE{ } SERVICE IS AVAILABLE



            } // __ END FOR{ } SERVICES PER DAY

            countDay ++;

        } // __ END FOR{ } DAYS
    }

}
