package ai.pai.client.activity;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.view.View;
import android.widget.Toast;

import com.android.common.executors.ThreadExecutor;
import com.android.common.utils.LogHelper;
import com.android.views.progressbar.ProgressWheel;
import com.umeng.analytics.MobclickAgent;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import ai.pai.client.BuildConfig;
import ai.pai.client.R;
import ai.pai.client.adapter.FullScreenPhotoPageAdapter;
import ai.pai.client.beans.GroupPhotoItem;
import ai.pai.client.db.DBService;
import ai.pai.client.db.Preferences;
import ai.pai.client.utils.HttpPostTask;
import ai.pai.client.utils.UmengEvent;
import ai.pai.client.utils.UrlContainer;
import ai.pai.client.views.HackyViewPager;

public class PhotoFullScreenActivity extends BaseActivity implements View.OnClickListener, ViewPager.OnPageChangeListener {


    private ArrayList<GroupPhotoItem> photoList;
    private GroupPhotoItem currentPhotoItem;
    private ProgressWheel spinner;
    private SavePhotoTask savePhotoTask;
    private FullScreenPhotoPageAdapter photoPageAdapter;
    private HttpPostTask fetchPhotosTask;
    private int currentGroupPhotoId;
    private boolean fromGroupPage;

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

        photoList = (ArrayList<GroupPhotoItem>) getIntent().getSerializableExtra("list");
        currentPhotoItem = (GroupPhotoItem) getIntent().getSerializableExtra("photo_item");
        fromGroupPage = getIntent().getBooleanExtra("fromGroup",false);
        if(fromGroupPage){
            currentGroupPhotoId=  DBService.getInstance(this).getCurrentIdByGroupId(currentPhotoItem.groupId);
        }
        if(photoList.size()>=300){
            currentGroupPhotoId = 0;
        }
        HackyViewPager photoPager = (HackyViewPager) findViewById(R.id.pager_photo);
        spinner = (ProgressWheel)findViewById(R.id.wheel_wait_http);
        photoPageAdapter = new FullScreenPhotoPageAdapter(this, photoList,photoPager);
        photoPager.setAdapter(photoPageAdapter);
        photoPager.addOnPageChangeListener(this);
        photoPager.setCurrentItem(photoList.indexOf(currentPhotoItem));
        findViewById(R.id.btn_back_full_screen).setOnClickListener(this);
        findViewById(R.id.btn_download_full_screen).setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_back_full_screen:
                finish();
                break;
            case R.id.btn_download_full_screen:
                MobclickAgent.onEvent(this, UmengEvent.fullscreen_download_btn_click);
                if(currentPhotoItem.photoFrom==1 && TextUtils.isEmpty(currentPhotoItem.mediumPhotoUrl) && TextUtils.isEmpty(currentPhotoItem.rawPhotoUrl)){
                    Toast.makeText(this,R.string.photo_need_buy,Toast.LENGTH_SHORT).show();
                    return;
                }
                if(savePhotoTask!=null && savePhotoTask.getStatus()== AsyncTask.Status.RUNNING){
                    savePhotoTask.cancel(true);
                }
                savePhotoTask = new SavePhotoTask(this);
                savePhotoTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(),
                        currentPhotoItem.photoUrl);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(savePhotoTask!=null && savePhotoTask.getStatus()== AsyncTask.Status.RUNNING){
            savePhotoTask.cancel(true);
        }
    }

    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
        if(position==photoList.size()-1){
            if(fetchPhotosTask!=null && fetchPhotosTask.getStatus()== AsyncTask.Status.RUNNING){
                Toast.makeText(this,R.string.please_wait,Toast.LENGTH_SHORT).show();
            }
        }
    }

    @Override
    public void onPageSelected(int position) {
        currentPhotoItem = photoList.get(position);
        if(position>=photoList.size()-1){
            Bundle bundle = new Bundle();
            bundle.putString("group_id",currentPhotoItem.groupId);
            bundle.putString("current_id",String.valueOf(currentGroupPhotoId));
            loadMoreGroupPhotos(bundle);
        }
    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    private synchronized void loadMoreGroupPhotos(final Bundle bundle){
        if(fetchPhotosTask!=null && fetchPhotosTask.getStatus()== AsyncTask.Status.RUNNING){
            return;
        }
        HashMap<String,String> params = new HashMap<>();
        params.put("group_id",bundle.getString("group_id"));
        params.put("user_id", Preferences.getInstance(this).getUserId());
        params.put("current_id",bundle.getString("current_id"));
        LogHelper.d(TAG,"loadMoreGroupPhotos with local currentId = "+bundle.getString("current_id"));

        fetchPhotosTask = new HttpPostTask(this,params) {
            ArrayList<GroupPhotoItem>  photoItems;
            String  groupId = bundle.getString("group_id");
            @Override
            protected boolean parseResponse(Context context, String response) {
                try{
                    JSONObject json = new JSONObject(response);
                    int status = json.getInt("status");
                    if(status == 200){
                        LogHelper.d(TAG,"group service loadMoreGroupPhotos  parseResponse status 200");
                        JSONObject info = json.getJSONObject("data");
                        if(currentGroupPhotoId==info.getInt("current_id")){
                            return false;
                        }
                        JSONArray sessionArray = info.getJSONArray("photos");
                        if(sessionArray!=null && sessionArray.length()>0) {
                            photoItems = new ArrayList<>();
                            for(int k = 0; k<sessionArray.length();k++){
                                JSONObject sessionObj = sessionArray.getJSONObject(k);
                                String sessionId = sessionObj.getString("session_id");
                                JSONArray photoArray = sessionObj.getJSONArray("photos");
                                if(photoArray!=null && photoArray.length()>0){
                                    for(int m = 0; m<photoArray.length();m++){
                                        JSONObject photoObj = photoArray.getJSONObject(m);
                                        GroupPhotoItem groupPhotoItem = GroupPhotoItem.parseFromJSON(photoObj);
                                        groupPhotoItem.sessionId = sessionId;
                                        photoItems.add(groupPhotoItem);
                                    }
                                }
                            }
                            LogHelper.d(TAG,"group service loadMoreGroupPhotos  get new photos ,count="+photoItems.size());
                        }

                        currentGroupPhotoId = info.getInt("current_id");
                        LogHelper.d(TAG,"loadMoreGroupPhotos with server currentId = "+currentGroupPhotoId+"groupId="+groupId);
                        return true;
                    }
                }catch (Exception e){
                    LogHelper.e(TAG,"group service loadMoreGroupPhotos error happen "+e);
                }
                return false;
            }

            @Override
            protected void onPostFail(Context context) {
                super.onPostFail(context);

            }

            @Override
            protected void onPostSuccess(Context context) {
                super.onPostSuccess(context);

                if(photoItems!=null && photoItems.size()>0){
                    ArrayList<GroupPhotoItem> newPhotos = new ArrayList<>();
                    for(GroupPhotoItem photoItem : photoItems){
                        if(!photoList.contains(photoItem)){
                            newPhotos.add(photoItem);
                        }
                    }
                    if(newPhotos.size()==0){
                        return;
                    }
                    photoList.addAll(newPhotos);
                    photoPageAdapter.addPhotos(newPhotos);
                }
            }
        };
        fetchPhotosTask.executeOnExecutor(ThreadExecutor.getInstance().getExecutor(), UrlContainer.GROUP_PHOTO_LIST_URL);
    }
     class SavePhotoTask extends AsyncTask<String, Integer, Boolean> {

        private Context context;
        private File file;
        private String name;

        public SavePhotoTask(Context context) {
            this.context = context;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            Toast.makeText(context, R.string.save_photo_processing, Toast.LENGTH_SHORT).show();
            spinner.setVisibility(View.VISIBLE);
            spinner.startSpinning();        }

        @Override
        protected Boolean doInBackground(String... params) {
            String  path = params[0];
            FileOutputStream fOut = null;
            HttpURLConnection conn = null;
            InputStream inStream = null;
            try {
                URL url = new URL(path);
                conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5 * 1000);
                conn.setRequestMethod("GET");
                inStream = conn.getInputStream();
                if(conn.getResponseCode() == HttpURLConnection.HTTP_OK){
                    File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
                    name = System.currentTimeMillis() + ".jpg";
                    file = new File(dir, name);
                    fOut = new FileOutputStream(file);
                    byte[] buffer = new byte[2048];
                    int len ;
                    while((len=inStream.read(buffer))!=-1){
                        fOut.write(buffer,0,len);
                        fOut.flush();
                    }
                    fOut.flush();
                    if(BuildConfig.isDevMode){
                        LogHelper.dfile("czy","保存照片到本地，图片链接地址为"+path);
                        LogHelper.dfile("czy","保存照片到本地，图片保存至"+file.getAbsolutePath()+"图片大小为"+file.length()+"字节\n\n");
                    }
                }
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                try{
                    inStream.close();
                    conn.disconnect();
                    fOut.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            return false;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            super.onPostExecute(result);
            spinner.stopSpinning();
            spinner.setVisibility(View.GONE);
            if (result) {
                Toast.makeText(context, R.string.save_photo_success, Toast.LENGTH_SHORT).show();
                try {
                    MediaStore.Images.Media.insertImage(context.getContentResolver(), file.getPath(), name, name);
                    Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
                    Uri uri = Uri.fromFile(file);
                    intent.setData(uri);
                    context.sendBroadcast(intent);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            } else {
                Toast.makeText(context, R.string.save_photo_fail, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
