package epson.print.storage.evernote;

import android.content.Context;

import com.epson.iprint.storage.StorageItem;
import com.epson.iprint.storage.StorageServiceClient;
import com.evernote.client.android.EvernoteSession;
import com.evernote.edam.error.EDAMNotFoundException;
import com.evernote.edam.error.EDAMSystemException;
import com.evernote.edam.error.EDAMUserException;
import com.evernote.edam.notestore.NoteFilter;
import com.evernote.edam.notestore.NoteList;
import com.evernote.edam.type.Data;
import com.evernote.edam.type.Note;
import com.evernote.edam.type.NoteSortOrder;
import com.evernote.edam.type.Notebook;
import com.evernote.edam.type.Resource;
import com.evernote.edam.type.ResourceAttributes;
import com.evernote.thrift.TException;
import com.google.common.primitives.UnsignedBytes;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Vector;

import epson.common.Utils;
import epson.print.Util.EPLog;

public class EvernoteRequest {
    private static final String NOTE_PREFIX = "<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\"><en-note>";
    private static final String NOTE_SUFFIX = "</en-note>";
    private static final String TAG = "EvernoteRequest";
    private static final String URI_FILE_DEMI = "/";
    private static final String URI_FILE_FEED = "root";
    private Context mContext = null;

    public EvernoteRequest(Context context) {
        mContext = context;
    }

    public StorageItem getFeedItem() {
        StorageItem storageItem = new StorageItem();
        storageItem.path = URI_FILE_FEED;
        storageItem.type = StorageItem.ItemType.DIRECTORY;
        return storageItem;
    }

    public List<StorageItem> getItemList(StorageItem storageItem) throws IOException, TException, EDAMUserException, EDAMSystemException, EDAMNotFoundException {
        EvernoteSession evernoteSession = EvernoteClient.getEvernoteSession(mContext);
        if (storageItem.type == StorageItem.ItemType.DIRECTORY) {
            ArrayList arrayList = new ArrayList();
            if (URI_FILE_FEED.equals(storageItem.path)) {
                for (Notebook next : evernoteSession.getEvernoteClientFactory().getNoteStoreClient().listNotebooks()) {
                    StorageItem storageItem2 = new StorageItem();
                    storageItem2.path = next.getGuid();
                    storageItem2.name = next.getName();
                    storageItem2.type = StorageItem.ItemType.DIRECTORY;
                    storageItem2.userInfo = next;
                    arrayList.add(storageItem2);
                }
            } else {
                NoteFilter noteFilter = new NoteFilter();
                noteFilter.setOrder(NoteSortOrder.UPDATED.getValue());
                noteFilter.setAscending(false);
                noteFilter.setNotebookGuid(storageItem.path);
                Map<String, Integer> notebookCounts = evernoteSession.getEvernoteClientFactory().getNoteStoreClient().findNoteCounts(noteFilter, false).getNotebookCounts();
                if (notebookCounts != null) {
                    Integer num = notebookCounts.get(storageItem.path);
                    if (num == null) {
                        return new ArrayList();
                    }
                    NoteList findNotes = evernoteSession.getEvernoteClientFactory().getNoteStoreClient().findNotes(noteFilter, 0, num.intValue());
                    if (findNotes == null) {
                        return new ArrayList();
                    }
                    for (Note resources : findNotes.getNotes()) {
                        List<Resource> resources2 = resources.getResources();
                        if (resources2 != null) {
                            for (Resource next2 : resources2) {
                                if (next2.getAttributes().getFileName() != null) {
                                    StorageItem storageItem3 = new StorageItem();
                                    storageItem3.path = next2.getGuid();
                                    storageItem3.name = next2.getAttributes().getFileName();
                                    storageItem3.type = StorageItem.ItemType.FILE;
                                    storageItem3.userInfo = next2;
                                    arrayList.add(storageItem3);
                                }
                            }
                        }
                    }
                }
            }
            return arrayList;
        }
        throw new IOException("Invalid ItemType");
    }

    private StorageItem getUploadFolder() throws TException, EDAMUserException, EDAMSystemException {
        StorageItem storageItem = null;
        for (Notebook next : EvernoteClient.getEvernoteSession(mContext).getEvernoteClientFactory().getNoteStoreClient().listNotebooks()) {
            if ("Epson iPrint".equals(next.getName())) {
                storageItem = new StorageItem();
                storageItem.path = next.getGuid();
                storageItem.name = next.getName();
                storageItem.type = StorageItem.ItemType.DIRECTORY;
                storageItem.userInfo = next;
            }
        }
        return storageItem;
    }

    private StorageItem newUploadFolder() throws TException, EDAMUserException, EDAMSystemException {
        EvernoteSession evernoteSession = EvernoteClient.getEvernoteSession(mContext);
        Notebook notebook = new Notebook();
        notebook.setName("Epson iPrint");
        Notebook createNotebook = evernoteSession.getEvernoteClientFactory().getNoteStoreClient().createNotebook(notebook);
        StorageItem storageItem = new StorageItem();
        storageItem.path = createNotebook.getGuid();
        storageItem.name = createNotebook.getName();
        storageItem.type = StorageItem.ItemType.DIRECTORY;
        storageItem.userInfo = createNotebook;
        return storageItem;
    }

    class UploadHandler {
        private boolean canceled = false;

        UploadHandler() {
        }

        private StorageServiceClient.ProcessError upload(StorageItem storageItem, String str, String str2) throws FileNotFoundException, NoSuchAlgorithmException, TException, EDAMUserException, EDAMSystemException, EDAMNotFoundException {
            EvernoteSession evernoteSession = EvernoteClient.getEvernoteSession(EvernoteRequest.mContext);
            File file = new File(str);
            Resource resource = new Resource();
            resource.setData(EvernoteRequest.readFileAsData(file.getAbsolutePath()));
            resource.setMime(Utils.getExtType(Utils.getExtention(file.getAbsolutePath())));
            ResourceAttributes resourceAttributes = new ResourceAttributes();
            resourceAttributes.setFileName(str2);
            resource.setAttributes(resourceAttributes);
            Note note = new Note();
            note.setTitle(str2);
            note.setCreated(System.currentTimeMillis());
            note.setUpdated(System.currentTimeMillis());
            note.setActive(true);
            note.setResourcesIsSet(true);
            note.setNotebookGuid(((Notebook) storageItem.userInfo).getGuid());
            Vector vector = new Vector();
            vector.add(resource);
            note.setResources(vector);
            note.setContent("<?xml version=\"1.0\" encoding=\"UTF-8\"?><!DOCTYPE en-note SYSTEM \"http://xml.evernote.com/pub/enml2.dtd\"><en-note><p>Epson iPrint scan data:</p><en-media type=\"" + resource.getMime() + "\" hash=\"" + EvernoteRequest.bytesToHex(resource.getData().getBodyHash()) + "\"/>" + "</en-note>");
            evernoteSession.getEvernoteClientFactory().getNoteStoreClient().createNote(note);
            return canceled ? StorageServiceClient.ProcessError.CANCELED : StorageServiceClient.ProcessError.NONE;
        }

        private void cancel() {
            canceled = true;
            EPLog.d(EvernoteRequest.TAG, "Upload Canceled！！");
        }
    }

    class DownloadHandler {
        private boolean canceled = false;

        DownloadHandler() {
        }

        private StorageServiceClient.ProcessError download(String str, String str2) throws TException, EDAMUserException, EDAMSystemException, EDAMNotFoundException, IOException {
            Resource resource = EvernoteClient.getEvernoteSession(EvernoteRequest.mContext).getEvernoteClientFactory().getNoteStoreClient().getResource(str, true, false, true, false);
            resource.getAttributes().getFileName();
            Data data = resource.getData();
            FileOutputStream fileOutputStream = new FileOutputStream(new File(str2));
            try {
                fileOutputStream.write(data.getBody());
                try {
                    fileOutputStream.close();
                } catch (IOException unused) {
                }
                return canceled ? StorageServiceClient.ProcessError.CANCELED : StorageServiceClient.ProcessError.NONE;
            } catch (IOException e) {
                throw e;
            } catch (Throwable th) {
                try {
                    fileOutputStream.close();
                } catch (IOException unused2) {
                }
                throw th;
            }
        }

        private void cancel() {
            canceled = true;
        }
    }

    public StorageServiceClient.ProcessError handleException(Exception exc) {
        EPLog.e(TAG, "handleException");
        String message = exc.getMessage();
        if (message == null && exc.getCause() != null) {
            message = exc.getCause().getMessage();
        }
        if (message != null) {
            EPLog.e(TAG, message);
        }
        EvernoteClient.logout(mContext);
        return StorageServiceClient.ProcessError.ERROR;
    }

    private UploadHandler getUploadHandler() {
        return new UploadHandler();
    }

    private DownloadHandler getDownloadHandler() {
        return new DownloadHandler();
    }

    private static Data readFileAsData(String str) throws FileNotFoundException, NoSuchAlgorithmException {
        FileInputStream fileInputStream = new FileInputStream(str);
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        byte[] bArr = new byte[10240];
        while (true) {
            try {
                int read = fileInputStream.read(bArr);
                if (read >= 0) {
                    byteArrayOutputStream.write(bArr, 0, read);
                }
            } catch (IOException e) {
                e.printStackTrace();
            } catch (Throwable th) {
                try {
                    fileInputStream.close();
                } catch (IOException unused) {
                }
                throw th;
            }
            try {
                break;
            } catch (IOException unused2) {
            }
        }
        fileInputStream.close();
        byte[] byteArray = byteArrayOutputStream.toByteArray();
        Data data = new Data();
        data.setSize(byteArray.length);
        data.setBodyHash(MessageDigest.getInstance("MD5").digest(byteArray));
        data.setBody(byteArray);
        return data;
    }

    private static String bytesToHex(byte[] bArr) {
        StringBuilder sb = new StringBuilder();
        for (byte b : bArr) {
            byte b2 = b & UnsignedBytes.MAX_VALUE;
            if (b2 < 16) {
                sb.append('0');
            }
            sb.append(Integer.toHexString(b2));
        }
        return sb.toString();
    }
}
