package com.example.sleep;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


import com.example.ViewPagerAdapter;
import com.example.sleep.database.GetRecord;
import com.example.sleep.database.RecordBean;
import com.example.sleep.service.GoSleepService;


import static com.example.sleep.database.GetRecord.getRecord;


/**
 * 一开始的主界面
 */
public class MainScreen extends FragmentActivity {

    private static final int REQUEST_READ_EXTERNAL_STORAGE = 1;
    private long exitTime = 0;
    private ViewPager viewPager;
    private TabLayout tabLayout;
    private Button backRl;


    //初始化
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        readLog();
        /*initView();*/
        startGoSleepService();

        viewPager = findViewById(R.id.viewPager);
        backRl = findViewById(R.id.btn_AfterSleep);
        backRl.setOnClickListener(v -> finish());
        tabLayout = findViewById(R.id.tabLayout);

        ViewPagerAdapter adapter = new ViewPagerAdapter(getSupportFragmentManager());
        adapter.addFragment(new SleepFragment(), "睡眠");
        adapter.addFragment(new DreamAnalyszeScreen(), "解梦");
        adapter.addFragment(new Share(), "分享");
        adapter.addFragment(new SuggestScreen(), "报告");

        viewPager.setAdapter(adapter);
        tabLayout.setupWithViewPager(viewPager);

        // 检查权限
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            // 请求权限
            ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_EXTERNAL_STORAGE);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

        if (requestCode == REQUEST_READ_EXTERNAL_STORAGE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限已获得
            } else {
                // 权限被拒绝
                Toast.makeText(this, "Permission Denied!", Toast.LENGTH_SHORT).show();
            }
        }
    }


    //按钮
    public void ClickRecord(View v) {
        Intent i = new Intent();
        i.setClass(MainScreen.this, CalendarPage.class);
        MainScreen.this.startActivity(i);
        MainScreen.this.finish();
    }

    //按下返回键的效果
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - exitTime > 2000) {
                Toast.makeText(getApplicationContext(), "再按一次退出程序", Toast.LENGTH_SHORT).show();
                exitTime = System.currentTimeMillis();
            } else {
                finish();
                System.exit(0);
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    //读睡眠记录，判断是否异常退出
    private void readLog() {
        RecordBean mRecord;
        GetRecord mGetRecord = getRecord();
        mRecord = mGetRecord.getLatestRecord();
        if (mRecord != null) {
            if (!mRecord.getValid()) {
                Intent i = new Intent();
                i.setClass(MainScreen.this, SleepMonitoringScreen.class);
                MainScreen.this.startActivity(i);
                MainScreen.this.finish();
            }
        }
    }

    public void startGoSleepService() {
        Intent ifSleepIntent = new Intent(this, GoSleepService.class);
        this.startService(ifSleepIntent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
