/*
 * Copyright (C) 2012 University of Washington
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */

package org.odk.collect.android.widgets;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.support.annotation.StringRes;
import android.support.v4.view.ViewCompat;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import org.javarosa.core.model.data.IAnswerData;
import org.javarosa.core.model.data.StringData;
import org.javarosa.form.api.FormEntryPrompt;
import org.odk.collect.android.R;
import org.odk.collect.android.activities.DrawActivity;
import org.odk.collect.android.activities.FormEntryActivity;
import org.odk.collect.android.application.Collect;
import org.odk.collect.android.logic.FormController;
import org.odk.collect.android.utilities.FileUtils;
import org.odk.collect.android.utilities.MediaUtils;
import org.odk.collect.android.views.ButtonBuilder;

import java.io.File;

/**
 * Free drawing widget.
 *
 * @author BehrAtherton@gmail.com
 */
public class DrawWidget extends QuestionWidget implements IBinaryWidget {
  private final static String t = "DrawWidget";
  /**
   * Name of the directory containing default images.
   */
  public static final String DEFAULTS_DIR = "defaults";

  private Button mDrawButton;
  private String mBinaryName;
  private String mInstanceFolder;
  private ImageView mImageView;
  private TextView mErrorTextView;

  public DrawWidget(final Context context, final FormEntryPrompt prompt) {
    super(context, prompt);

    mBinaryName = prompt.getAnswerText();
    final boolean hasImage = mBinaryName != null;

    mErrorTextView = new TextView(context);
    mErrorTextView.setId(QuestionWidget.newUniqueId());
    mErrorTextView.setText("Selected file is not a valid image");

    final FormController formController = Collect.getInstance().getFormController();
    mInstanceFolder = formController.getInstancePath().getParent();

    setOrientation(LinearLayout.VERTICAL);
    LayoutParams params = new LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
    // setup Blank Image Button
    final ButtonBuilder drawButtonBuilder = new ButtonBuilder(context);
    drawButtonBuilder.withParent(this);
    final @StringRes int buttonTextResID = prompt.isReadOnly() ? R.string.view_image : R.string.draw_image;
    drawButtonBuilder.withTextResource(buttonTextResID);
    mDrawButton = drawButtonBuilder.build();
    mDrawButton.setLayoutParams(params);
    final OnClickListener onClickListener = new OnClickListener() {
      @Override
      public void onClick(View v) {
        if (prompt.isReadOnly()) {
          File f = new File(mInstanceFolder + File.separator + mBinaryName);
          Collect.getInstance().getViewImageActivityDelagate().launchViewImageActivity(context, f, mImageView);
        } else {
          launchDrawActivity();
        }
      }
    };
    // launch capture intent on click
    mDrawButton.setOnClickListener(onClickListener);

    // finish complex layout
    addView(mDrawButton);
    addView(mErrorTextView);
    mErrorTextView.setVisibility(View.GONE);

    // Only add the imageView if the user has signed
    if (hasImage) {
      mImageView = new ImageView(context);
      mImageView.setScaleType(ImageView.ScaleType.CENTER);
      mImageView.setId(QuestionWidget.newUniqueId());

      final File f = new File(mInstanceFolder + File.separator + mBinaryName);
      final File defaultFile = getDefaultFile();

      Bitmap bmp = FileUtils.getBitmapScaledToDisplay(context, f);
      final Bitmap defaultBitmap = FileUtils.getBitmapScaledToDisplay(context, defaultFile);

      Bitmap displayBitmap;
      if (bmp == null) {
        displayBitmap = defaultBitmap;
      } else if (defaultBitmap == null) {
        displayBitmap = bmp;
      } else {
        displayBitmap = MediaUtils.getCombinedBitmaps(defaultBitmap, bmp, defaultBitmap.getWidth(), defaultBitmap
            .getHeight());
      }

      mImageView.setImageDrawable(null);
      mImageView.setImageBitmap(displayBitmap);

      mImageView.setPadding(10, 10, 10, 10);
      mImageView.setBackgroundColor(Color.WHITE);
      mImageView.setAdjustViewBounds(true);
      mImageView.setOnClickListener(onClickListener);
      ViewCompat.setTransitionName(mImageView, context.getString(R.string.view_image_transition_name));

      mImageView.setLayoutParams(params);

      addView(mImageView);
    }
  }

  private File getDefaultFile() {
    final File defaultDir = new File(mInstanceFolder, DEFAULTS_DIR);
    final File f = new File(defaultDir, mBinaryName);
    return new File(defaultDir, mBinaryName);
  }

  private void launchDrawActivity() {
    mErrorTextView.setVisibility(View.GONE);
    final DrawActivity.DrawActivityDelegate drawActivityDelegate = Collect.getInstance().getDrawActivityDelegate();
    final Context context = getContext();
    final boolean hasDelegate = drawActivityDelegate != null;
    if (hasDelegate) {
      Intent i = drawActivityDelegate.getDrawActivityIntent(context);
      i.putExtra(DrawActivity.OPTION, DrawActivity.OPTION_DRAW);
      if (mBinaryName != null) {
        File f = new File(mInstanceFolder + File.separator + mBinaryName);
        i.putExtra(DrawActivity.REF_IMAGE, Uri.fromFile(f));
      }
      final File defaultFile = getDefaultFile();
      if (defaultFile != null && defaultFile.exists()) {
        i.putExtra(DrawActivity.REF_BACKGROUND, Uri.fromFile(defaultFile));
      }
      i.putExtra(DrawActivity.EXTRA_OUTPUT,
          Uri.fromFile(new File(Collect.TMPFILE_PATH)));

      try {
        Collect.getInstance().getFormController()
            .setIndexWaitingForData(mPrompt.getIndex());
        ((Activity) context).startActivityForResult(i, FormEntryActivity.DRAW_IMAGE);
      } catch (ActivityNotFoundException e) {
        Toast.makeText(
            context,
            context.getString(R.string.activity_not_found,
                "draw image"), Toast.LENGTH_SHORT).show();
        Collect.getInstance().getFormController()
            .setIndexWaitingForData(null);
      }
    } else {
      Toast.makeText(context, R.string.draw_image_activity_fail, Toast.LENGTH_LONG).show();
    }
  }

  private void deleteMedia() {
    // get the file path and delete the file
    String name = mBinaryName;
    // clean up variables
    mBinaryName = null;
    // delete from media provider
    int del = MediaUtils.deleteImageFileFromMediaProvider(mInstanceFolder
        + File.separator + name);
    Log.i(t, "Deleted " + del + " rows from media content provider");
  }

  @Override
  public void clearAnswer() {
    // remove the file
    deleteMedia();
    mImageView.setImageBitmap(null);
    mErrorTextView.setVisibility(View.GONE);

    // reset buttons
    mDrawButton.setText(getContext().getString(R.string.draw_image));
  }

  @Override
  public IAnswerData getAnswer() {
    if (mBinaryName != null) {
      return new StringData(mBinaryName);
    } else {
      return null;
    }
  }

  @Override
  public void setBinaryData(Object answer) {
    // you are replacing an answer. delete the previous image using the
    // content provider.
    if (mBinaryName != null) {
      //deleteMedia();
    }

    File newImage = (File) answer;
    if (newImage.exists()) {
      mBinaryName = newImage.getName();
      Log.i(t, "Setting current answer to " + newImage.getName());
    } else {
      Log.e(t, "NO IMAGE EXISTS at: " + newImage.getAbsolutePath());
    }

    Collect.getInstance().getFormController().setIndexWaitingForData(null);
  }

  @Override
  public void setFocus(Context context) {
    // Hide the soft keyboard if it's showing.
    InputMethodManager inputManager = (InputMethodManager) context
        .getSystemService(Context.INPUT_METHOD_SERVICE);
    inputManager.hideSoftInputFromWindow(this.getWindowToken(), 0);
  }

  @Override
  public boolean isWaitingForBinaryData() {
    return mPrompt.getIndex().equals(
        Collect.getInstance().getFormController()
            .getIndexWaitingForData());
  }

  @Override
  public void cancelWaitingForBinaryData() {
    Collect.getInstance().getFormController().setIndexWaitingForData(null);
  }

  @Override
  public void setOnLongClickListener(OnLongClickListener l) {
    mDrawButton.setOnLongClickListener(l);
    if (mImageView != null) {
      mImageView.setOnLongClickListener(l);
    }
  }

  @Override
  public void cancelLongPress() {
    super.cancelLongPress();
    mDrawButton.cancelLongPress();
    if (mImageView != null) {
      mImageView.cancelLongPress();
    }
  }
}
