package com.hjx.miaohongentry.activity;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.MediaPlayer;
import android.os.Environment;
import android.support.v4.app.ActivityCompat;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.TextView;

import com.hjx.miaohongentry.R;
import com.hjx.miaohongentry.db.MHDataManager;
import com.hjx.miaohongentry.update.UpdateChecker;
import com.hjx.miaohongentry.util.Constants;
import com.hjx.miaohongentry.util.SpUtils;
import com.hjx.miaohongentry.util.StatisUtils;
import com.tencent.bugly.crashreport.CrashReport;

import java.io.File;
import java.io.FileDescriptor;
import java.io.IOException;
import java.io.RandomAccessFile;

public class MainActivity extends Activity {

    private static final int REQUEST_EXTERNAL_STORAGE = 0x99;
    private Button startBtn;
    private ImageButton chooseBtn;
    private final int REQUEST_CODE_CHOOSE_BOOK = 0x01;
    private TextView bookTextView;
    private String bookInfo;
    private TextView tv_write_time;
    private TextView tv_today_num;
    private TextView tv_total_num;

    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE};

    public static void verifyStoragePermissions(Activity activity) {
        // Check if we have write permission
        int permission = ActivityCompat.checkSelfPermission(activity,
                Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(activity, PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE);
        }
    }

    private void initView(){
        startBtn = (Button) findViewById(R.id.btn_start);
        startBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(MainActivity.this, WordActivity.class);
                intent.putExtra("bookInfo",bookInfo);
                startActivity(intent);
            }
        });
        chooseBtn = (ImageButton)findViewById(R.id.btn_choose);
        chooseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int idx = SpUtils.getInt(MainActivity.this,Constants.SP_BOOK_CHOSEN_ID,0);
                Intent intent = new Intent(MainActivity.this, ChooseBookActivity.class);
                intent.putExtra("idx",idx);
                startActivityForResult(intent,REQUEST_CODE_CHOOSE_BOOK);
            }
        });
        bookTextView = (TextView)findViewById(R.id.tv_publish_name);
        bookInfo = SpUtils.getString(this,Constants.SP_BOOK_CHOSEN_INFO,"人民教育出版社#一年级#上册");
        if(!bookInfo.isEmpty()){
            String info[] = bookInfo.split("#");
            if(info.length == 3){
                String bookStr = info[1] + info[2] + " " + info[0];
                bookTextView.setText(bookStr);
            }
        }

        tv_write_time = findViewById(R.id.write_time);
        tv_today_num = findViewById(R.id.today_num);
        tv_total_num = findViewById(R.id.total_num);
        showStatisView();
    }

    private void showStatisView(){
        if(!StatisUtils.isToday(this)){
            StatisUtils.setTodayNum(this,0);
            StatisUtils.setTodayTime(this,0);
            StatisUtils.setToday(this);
        }
        tv_total_num.setText(""+ StatisUtils.getTotalNum(this));
        tv_today_num.setText(""+ StatisUtils.getTodayNum(this));
        long mills = StatisUtils.getTodayTime(this);
        long min = mills / (1000 * 60);
        long sec = (mills - ( min * 60 * 1000)) / 1000;
        tv_write_time.setText(min + "分" + sec + "秒");

    }

    private void testSound(){
        MediaPlayer mPlayer = new MediaPlayer();
        try {
            RandomAccessFile mRandomAccessFile = new RandomAccessFile(
                    Environment.getExternalStorageDirectory().getPath() + File.separator
                            //    + "1.mp3",
                            + "DICTSOUND.BIN", "r");
            FileDescriptor mFileDescriptor = null;
            mFileDescriptor = mRandomAccessFile.getFD();
            mPlayer.reset();
            mPlayer.setDataSource(mFileDescriptor, 122295042, 3027/*mRandomAccessFile.length()*/);
            mPlayer.prepare();
            mPlayer.start();
            mRandomAccessFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        verifyStoragePermissions(this);
        CrashReport.initCrashReport(getApplicationContext(), "9c92cf01b2", false);
        setContentView(R.layout.activity_main);
        initView();
        MHDataManager.initDB(this, new InitCallback() {
            @Override
            public void onError(IOException e) {

            }

            @Override
            public void onSucess() {

            }
        });
        updateVersion();
    }

    private void saveBookInfo( String bookStr){
        SpUtils.putString(MainActivity.this, Constants.SP_BOOK_CHOSEN_INFO,bookStr);
    }

    private void saveBookIdx(String id ){
        try {
            int idx = Integer.parseInt(id);
            SpUtils.putInt(MainActivity.this, Constants.SP_BOOK_CHOSEN_ID,idx);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

        switch (requestCode) {
            case REQUEST_CODE_CHOOSE_BOOK:
                if(resultCode == ChooseBookActivity.RESULT_CODE_CHOOSE_SECCESS){
                    String id = data.getStringExtra("id");
                    String press = data.getStringExtra("press");
                    String grade = data.getStringExtra("grade");
                    String reactos = data.getStringExtra("reactos");
                    String bookStr = grade + reactos + " " + press;
                    bookTextView.setText(bookStr);
                    bookInfo = press + "#" + grade + "#" + reactos;
                    saveBookInfo(bookInfo);
                    saveBookIdx(id);
                }
                break;
            default:
                break;
        }
    }

    @Override
    protected  void onResume(){
        super.onResume();
        showStatisView();
    }

    private void updateVersion(){
        UpdateChecker checker = new UpdateChecker(this);
        checker.checkForUpdates();
    }



}
