package org.ntlab.acanthus_client.views.main_menu_ui.edit;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;


import org.ntlab.acanthus_client.Acanthus;
import org.ntlab.acanthus_client.R;
import org.ntlab.acanthus_client.databinding.FragmentEditBinding;
import org.ntlab.acanthus_client.entities.AidJson;
import org.ntlab.acanthus_client.entities.Animation;
import org.ntlab.acanthus_client.entities.AnimationJson;
import org.ntlab.acanthus_client.entities.WorkJson;
import org.ntlab.acanthus_client.views.paint.PaintActivity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;import java.util.Map.Entry;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;


public class EditFragment extends Fragment {

    private EditViewModel editViewModel;
    private FragmentEditBinding binding;
    private ArrayList<Integer> aidList;
    private ArrayList<AnimationJson> AnimationJsonList;
    private ArrayList<String> nameList;
    private ArrayList<String> lastUpDateList;
    private HashMap<Integer, String> nameHashMap;
    private HashMap<Integer, String> lastUpDateHashMap;
    private Integer AnimationAid;
    private String AnimationName;
    private String AnimationLastUpDate;

    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        editViewModel =
                new ViewModelProvider(this).get(EditViewModel.class);

        binding = FragmentEditBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        return root;
    }

    //-------------------------------------------------------------------------------------------------
    //listView
    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);

        editViewModel = new ViewModelProvider(this).get(EditViewModel.class);

        Acanthus acanthus = (Acanthus) getActivity().getApplication();
        Integer uid = 1;
        String token = "abc0";
        editViewModel.getWorkList(uid, token);
        aidList = new ArrayList<>();
        nameList = new ArrayList<>();
        lastUpDateList = new ArrayList<>();
        AnimationJsonList = new ArrayList<>();
        Map<Integer, String> nameHashMap = new HashMap<Integer, String>();
        Map<Integer, String> lastUpDateHashMap = new HashMap<Integer, String>();

        ListView listView = (ListView) getActivity().findViewById(R.id.list_view);

        editViewModel.getWorkJson().observe(getViewLifecycleOwner(), new Observer<WorkJson>() {

            //listViewの表示をしている
            @Override
            public void onChanged(@Nullable WorkJson workJson) {
                aidList = (ArrayList<Integer>) editViewModel.getWorkJson().getValue().getAid();
                AnimationJsonList = (ArrayList<AnimationJson>) acanthus.getAnimationJsonList();
                ArrayList<AnimationJson> workList = new ArrayList<>();

                if(AnimationJsonList != null){
                    for(int i=0; i<AnimationJsonList.size(); i++){
                        //acanthusのAnimationJsonListにとってきたaidが該当するかを探索する
                        if(aidList.contains(AnimationJsonList.get(i).getAid())){
                            AnimationName = AnimationJsonList.get(i).getAnimationName();
                            AnimationLastUpDate = AnimationJsonList.get(i).getLastUpdate();
                            AnimationAid =  AnimationJsonList.get(i).getAid();
                            nameHashMap.put(AnimationAid, AnimationName);
                            lastUpDateHashMap.put(AnimationAid, AnimationLastUpDate);

//                            nameList.add(AnimationName);
//                            lastUpDateList.add(AnimationLastUpDate);
                            workList.add(AnimationJsonList.get(i));
                        }
                    }
                }

                //--------------------------------------------------------------------------------------------------------------------
                //sort
                List<Entry<Integer, String>> list_entries = new ArrayList<Entry<Integer, String>>(lastUpDateHashMap.entrySet());
                Collections.sort(list_entries, new Comparator<Entry<Integer, String>>() {
                    public int compare(Entry<Integer, String> obj1, Entry<Integer, String> obj2) {
                        // 降順(昇順はObj1とObj2を変える)
                        return obj2.getValue().compareTo(obj1.getValue());
                    }
                });
                for(Entry<Integer, String> entry : list_entries) {
                    lastUpDateList.add(entry.getValue());
                    nameList.add(nameHashMap.get(entry.getKey()));
                }
                //--------------------------------------------------------------------------------------------------------------------


                BaseAdapter adapter = new WorkListViewAdapter(getActivity(),
                        R.layout.work_list, nameList, lastUpDateList);
                listView.setAdapter(adapter);

                listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
                        transitionPaintActivity(workList.get(position));
                    }
                });
            }


        });

        editViewModel.getAidJson().observe(getViewLifecycleOwner(), new Observer<AidJson>() {
            //作品の新規作成時の処理
            @Override
            public void onChanged(AidJson aidJson) {
                acanthus.setAid(aidJson.getAid());
                transitionPaintActivity();
            }
        });

    }
    //-------------------------------------------------------------------------------------------------

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Button appButton = view.findViewById(R.id.Paint_button);
        Integer uid = 1;
        String token = "abc0";

        //編集ボタン
        Button editButton = view.findViewById(R.id.Edit_button);

        appButton.setOnClickListener(v -> {
            Acanthus acanthus = (Acanthus) getActivity().getApplication();
            //Integer uid = acanthus.getPreferenceUid();
            String name = ((EditText)view.findViewById(R.id.AnimationName)).getText().toString();
            //String token = acanthus.getPreferenceToken();
            //Integer aid = editViewModel.startWorkEdit(uid, name, token);
            editViewModel.startWorkEdit(uid, name, token);
        });

        editButton.setOnClickListener(v -> {
            Acanthus acanthus = (Acanthus) getActivity().getApplication();
            //dummy---------
            Integer aid = 1111;
            //--------------
            acanthus.setAid(aid);
            transitionPaintActivity();
        });
    }

    //-----------------------------------------------------------------
    // 画面遷移
    private void transitionPaintActivity() {
        Acanthus acanthus = (Acanthus) getActivity().getApplication();
        Intent intent = new Intent(acanthus, PaintActivity.class);
        startActivity(intent);
    }

    //各作品毎の画面遷移
    private void transitionPaintActivity(AnimationJson animationJson) {
        Acanthus acanthus = (Acanthus) getActivity().getApplication();
        Intent intent = new Intent(acanthus, PaintActivity.class);
        acanthus.setAid(animationJson.getAid());
        startActivity(intent);
    }


}