package com.example.diary;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class DiaryActivity extends Activity {
	public static final String DIARY_DIR = "diary";
	public static final String LOGFILENAME = "diarylog.txt";
	private Button saveButton;
	private TextView fileNameView;
	private EditText diaryEdit;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_diary);
        fileNameView = (TextView)findViewById(R.id.fileNameView);
        saveButton = (Button)findViewById(R.id.saveButton);
        diaryEdit = (EditText)findViewById(R.id.diaryEdit);
        
        Bundle b = getIntent().getExtras();
        if (b != null) {
          getDiary(b.getString("FILENAME"));
        }
        else {
      	  SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
      	  String fileName = sdf.format(new Date());
      	  getDiary(fileName);
        }
        
        saveButton.setOnClickListener(new Button.OnClickListener()
        {  @Override public void onClick(View v) {
        	saveDiary(fileNameView.getText().toString());
           }
        });

    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_diary, menu);
        return true;
    }
 
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
  	  int itemid = item.getItemId();
  	  switch (itemid) {
  	  case R.id.openDiary:
  		  startActivity(new Intent("com.example.diary.LIST"));
  		  break;
  	  case R.id.logView:
  		  startActivity(new Intent("com.example.diary.LOG"));
  		  break;
  	  }
  	  return true;
    }

    private void getDiary(String fileName) {
    	String text = "";
    	fileNameView.setText(fileName);    	
    	File diaryDir = getDir(DIARY_DIR, MODE_PRIVATE);
    	String filePath = diaryDir.getAbsolutePath()+File.separator + fileName;
    	File diary = new File(filePath);
    	FileInputStream fis;
    	try { fis = new FileInputStream(diary); }
    	catch (FileNotFoundException fnfe) {
    		Toast.makeText(this, "Diary " + fileName + " not found", Toast.LENGTH_LONG).show();
    		return;
    	}
    	try {
    		FileChannel fc = fis.getChannel();
    		MappedByteBuffer bb = fc.map(FileChannel.MapMode.READ_ONLY, 0, fc.size());
    		text = Charset.defaultCharset().decode(bb).toString();
    	}
    	catch (IOException ioe) {
    		Toast.makeText(this, "Error reading " + fileName, Toast.LENGTH_LONG).show();
    	}
    	finally { try { fis.close(); } catch (IOException e) {} }
    	diaryEdit.setText(text);
    }
    
    private void saveDiary(String fileName) {
    	File diaryDir = getDir(DIARY_DIR, MODE_PRIVATE);
    	String filePath = diaryDir.getAbsolutePath()+File.separator + fileName;
    	File diary = new File(filePath);
    	FileWriter fw;
    	try {
    		fw = new FileWriter(diary);
    	}
    	catch (IOException ioe) {
    		Toast.makeText(this, "Diary " + fileName + " not found", Toast.LENGTH_LONG).show();
    		return;
    	}
    	try {
    		BufferedWriter bw = new BufferedWriter(fw);
    		String text = diaryEdit.getText().toString();
    		bw.write(text, 0, text.length());
    		bw.close();
    		diaryLog("Diary entry saved, length " + text.length());
    	}
    	catch (IOException ioe) {
    		Toast.makeText(this, "Diary " + fileName + " not found", Toast.LENGTH_LONG).show();
    		return;   		
    	}
     	return;    	
    }
    
    private void diaryLog(String msg) {
    	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String timeStamp = sdf.format(new Date());
		String logEntry = timeStamp + ": " + msg + "\n";
    	try {
    		FileOutputStream fos = openFileOutput(LOGFILENAME, MODE_APPEND);
    		OutputStreamWriter osw = new OutputStreamWriter(fos);
    		osw.write(logEntry, 0, logEntry.length());
    		osw.close();
    	}
    	catch (IOException ioe) {
    		Log.e("DiaryActivity:diaryLog", ioe.toString());
    	}
    }
}
