package com.frank.markdown_editor.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.PopupMenu;
import android.widget.Toast;
import com.frank.markdown_editor.tools.IOTools;
import com.frank.markdown_editor.MD_Info;
import com.example.frank.test2.R;
import com.frank.markdown_editor.adapter.ListViewAdapter;
import com.frank.markdown_editor.analyze.AnalyzeString;
import com.frank.markdown_editor.tools.Sorts;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MainActivity extends Activity {
    private ListView listView;
    public static List<MD_Info> MDs,listSort;
    private  ListViewAdapter listViewAdapter;
    private Button more_but,add_but,help_but,about_but;
    private IOTools io;
    private StringBuilder builder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        io = new IOTools();
        io.dir();
        init();

        //添加文件按钮
        add_but = (Button) findViewById(R.id.add_but);
        add_but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShowInputMenu();
            }
        });

        //更多信息按钮
        more_but = (Button) findViewById(R.id.more_but);
        more_but.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                PopupMenu menu = new PopupMenu(getApplicationContext(),v);
                getMenuInflater().inflate(R.menu.more_menu_layout,menu.getMenu());
                menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        switch(item.getItemId()){
                            case R.id.about_but:
                                Intent aboutIntent = new Intent(MainActivity.this,AboutActivity.class);
                                startActivity(aboutIntent);
                                break;
                            case R.id.help_but:
                                Intent helpIntent = new Intent(MainActivity.this,HelpActivity.class);
                                startActivity(helpIntent);
                                break;
                        }
                        return false;
                    }
                });
                menu.show();
            }
        });

        listViewAdapter = new ListViewAdapter(this,MDs);

        listView = (ListView) findViewById(R.id.list_view);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                io = new IOTools();
                builder = io.fileRead(MDs.get(position).getName()+".md");
                Intent intent = new Intent(MainActivity.this,ViewPagerActivity.class);
                intent.putExtra("fileName",MDs.get(position).getName()+".md");
                intent.putExtra("fileContent",builder.toString());

                MD_Info md = MDs.get(position);
                MDs.remove(position);
                MDs.add(0,md);
                listViewAdapter.notifyDataSetChanged();

                startActivity(intent);
            }
        });
        listView.setAdapter(listViewAdapter);
    }

    //添加文件的弹出框
    private String ShowInputMenu() {
        final EditText inputFileName = new EditText(this);
        io = new IOTools();
        final String[] strContent = {""};

        AlertDialog.Builder builder = new AlertDialog.Builder(this);

        builder.setTitle("输入文件名:").setView(inputFileName)
                .setNegativeButton("Cancel", null);

        builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                strContent[0] = inputFileName.getText().toString();
                boolean b = io.addMDFile(strContent[0],MainActivity.this);
                if (b) {
                    long time = new Date().getTime();
                    MD_Info md_info = new MD_Info(strContent[0], time);
                    MDs.add(0, md_info);
                    ListViewAdapter adapter = new ListViewAdapter();
                    adapter.notifyDataSetChanged();
                    Intent intent = new Intent(MainActivity.this,ViewPagerActivity.class);
                    intent.putExtra("fileName",md_info.getName()+".md");
                    intent.putExtra("fileContent","");
                    startActivity(intent);
                }else {
                    Toast.makeText(MainActivity.this,"该名字已存在!\n\t请换一个.",Toast.LENGTH_SHORT).show();
                }
            }

        });
        builder.show();
//        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
//        inputMethodManager.toggleSoftInput(0, InputMethodManager.HIDE_NOT_ALWAYS);
        return strContent[0];
    }

    //初始化试图数据
    public void init() {
        io = new IOTools();
        MD_Info md_info;
        File[] files = io.getFiles(this);
        MDs = new ArrayList<MD_Info>();
        listSort = new ArrayList<MD_Info>();
        for (int i = 0; i < files.length; i++) {
            if (AnalyzeString.analyzeStr(files[i].getName()) == null){
                continue;
            }
            md_info = new MD_Info(
                    AnalyzeString.analyzeStr(files[i].getName()),
                    files[i].lastModified(),
                    io.getSize(files[i])
            );
            listSort.add(md_info);
        }
        MD_Info[]mdArr = listSort.toArray(new MD_Info[listSort.size()]);
        MDs.removeAll(listSort);
        MDs.addAll(Sorts.QuickSort_D(mdArr,0,mdArr.length-1));
        listSort = null;
    }

    @Override
    protected void onRestart() {
        super.onRestart();
        System.out.println("onRestart");
        listViewAdapter.notifyDataSetChanged();
    }

}