package ai.pai.client.activity;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import java.io.File;

import ai.pai.client.R;
import ai.pai.client.beans.GroupInfo;
import ai.pai.client.db.DBService;
import ai.pai.client.fragments.GroupPhotoFragment;
import ai.pai.client.fragments.GroupQRFragment;
import ai.pai.client.services.GroupService;
import ai.pai.client.utils.Constants;
import ai.pai.client.utils.GroupCreateUtils;
import ai.pai.client.utils.SystemUtils;

public class GroupActivity extends BaseActivity implements View.OnClickListener{

    private String groupId;
    private File photoFile;
    private String groupName;
    private int defaultAvatarId;
    private GroupQRFragment qrFragment;
    private GroupPhotoFragment photoFragment;

    private static final int TAKE_PHOTO_REQUEST_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_group);
        SystemUtils.setImmerseLayout(this,findViewById(R.id.title_layout));
        dealIntentBundle(getIntent());
        TextView title = (TextView)findViewById(R.id.title_bar_middle_txt);
        title.setText(groupName);
        ImageView groupAvatar = (ImageView)findViewById(R.id.iv_title_bar_avatar);
        if(defaultAvatarId>=0){
            groupAvatar.setImageResource(GroupCreateUtils.getDrawableIdForAvatar(defaultAvatarId));
        }else{
            groupAvatar.setVisibility(View.GONE);
        }
        findViewById(R.id.title_bar_back_layout).setOnClickListener(this);
        findViewById(R.id.title_bar_option_layout).setOnClickListener(this);
        findViewById(R.id.floating_btn_camera).setOnClickListener(this);
    }

    private void dealIntentBundle(Intent intent){
        if(intent.getSerializableExtra("group")==null){
            groupName = intent.getStringExtra("name");
            defaultAvatarId = intent.getIntExtra("avatar",0);
            showQRFragment();
        }else{
            GroupInfo info = (GroupInfo) intent.getSerializableExtra("group");
            groupId = info.groupId;
            groupName = info.groupName;
            if(TextUtils.isEmpty(groupName)){
                groupName = getString(R.string.default_group_name);
            }
            defaultAvatarId = info.groupAvatarId;
            if(!DBService.getInstance(this).isGroupExist(groupId)){
                info.lastEnterTime = System.currentTimeMillis();
                DBService.getInstance(this).addNewGroup(info);
            }else{
                DBService.getInstance(this).updateLastEnterTimeByGroupId(groupId,System.currentTimeMillis());
            }
            showPhotoFragment();
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.title_bar_back_layout:
                finish();
                break;
            case R.id.title_bar_option_layout:
                Intent intent = new Intent(GroupActivity.this,GroupSettingActivity.class);
                intent.putExtra("group_id",groupId);
                intent.putExtra("avatar_id",defaultAvatarId);
                intent.putExtra("group_name",groupName);
                startActivity(intent);
                break;
            case R.id.floating_btn_camera:
                if(TextUtils.isEmpty(groupId)){
                    if(qrFragment!=null && qrFragment.isAdded()){
                        groupId = qrFragment.getGroupId();
                    }
                    if(TextUtils.isEmpty(groupId)){
                        Toast.makeText(GroupActivity.this,R.string.group_detail_fetch_fail,Toast.LENGTH_SHORT).show();
                       finish();
                        return;
                    }
                }

                if(photoFragment==null){
                    showPhotoFragment();
                }
                photoFile = clickTakePhotoTab();
                break;
            default:
                break;
        }
    }

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

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(resultCode== Activity.RESULT_OK && requestCode==TAKE_PHOTO_REQUEST_CODE){
            if(photoFragment!=null && photoFragment.isAdded()){
//                Intent intent = new Intent(this,PhotoUploadActivity.class);
//                intent.putExtra("group_id",groupId);
//                intent.putExtra("photo_path",photoFile.getAbsolutePath());
//                startActivity(intent);
                uploadPhoto(photoFile.getAbsolutePath());
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void uploadPhoto(String path){
        if(TextUtils.isEmpty(path)){
            return;
        }

        Intent intent = new Intent(this, GroupService.class);
        Bundle bundle = new Bundle();
        bundle.putInt("command", GroupService.GroupCommand.COMMAND_UPLOAD_PHOTO);
        bundle.putString("group_id",groupId);
        bundle.putString("path",path);
        intent.putExtras(bundle);
        this.startService(intent);
    }

    private File clickTakePhotoTab(){
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File dir = new File(Constants.APP_IMAGE_DIR);
        dir.mkdirs();
        File photoFile = new File(dir.getAbsolutePath()+"/"+System.currentTimeMillis()+".jpg");
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
        startActivityForResult(intent,TAKE_PHOTO_REQUEST_CODE);
        return photoFile;
    }

    private void showQRFragment(){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if(qrFragment==null){
            qrFragment = new GroupQRFragment();
            Bundle bundle = new Bundle();
            bundle.putString("name",groupName);
            bundle.putInt("avatar",defaultAvatarId);
            qrFragment.setArguments(bundle);
            ft.add(R.id.content_fragment,qrFragment);
        }else{
            ft.show(qrFragment);
        }
        ft.commitAllowingStateLoss();
    }

    private void showPhotoFragment(){
        FragmentManager fm = getSupportFragmentManager();
        FragmentTransaction ft = fm.beginTransaction();
        if(photoFragment==null){
            photoFragment = new GroupPhotoFragment();
            Bundle bundle = new Bundle();
            bundle.putString("groupId",groupId);
            photoFragment.setArguments(bundle);
            ft.add(R.id.content_fragment,photoFragment);
        }else{
            ft.show(photoFragment);
        }
        ft.commitAllowingStateLoss();
    }
}
