package com.atr.tedit.utilitybar.state;

import android.database.Cursor;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;

import com.atr.tedit.R;
import com.atr.tedit.TEditActivity;
import com.atr.tedit.dialog.ErrorMessage;
import com.atr.tedit.dialog.OptionMessage;
import com.atr.tedit.file.descriptor.AndFile;
import com.atr.tedit.mainstate.Browser;
import com.atr.tedit.mainstate.Editor;
import com.atr.tedit.dialog.HelpDialog;
import com.atr.tedit.settings.Settings;
import com.atr.tedit.util.ShareHelper;
import com.atr.tedit.util.TEditDB;
import com.atr.tedit.utilitybar.UtilityBar;

/**
 * @author Adam T. Ryder
 * <a href="https://www.inventati.org/1337gallery">https://www.inventati.org/1337gallery</a>
 */

public class TextState extends UtilityState {
    public TextState(UtilityBar bar) {
        super(bar, UtilityBar.STATE_TEXT);

        boolean twoLayer = (bar.padding_w * 2 + bar.bWidth * 9 + bar.margin * 6) > bar.barWidth;

        Button settings = new Button(BAR.ctx);
        settings.setBackgroundResource(R.drawable.button_settings);
        settings.setId(R.id.nine);
        settings.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!BAR.ctx.getSettingsWindow().canOpen())
                    return;

                BAR.ctx.getSettingsWindow().open(true);
            }
        });

        Button newdoc = new Button(BAR.ctx);
        newdoc.setBackgroundResource(R.drawable.button_doc);
        newdoc.setId(R.id.zero);
        newdoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BAR.ctx.newDocument(TEditActivity.DEFAULTPATH, "");
            }
        });

        Button opendoc = new Button(BAR.ctx);
        opendoc.setBackgroundResource(R.drawable.button_dir);
        opendoc.setId(R.id.one);
        opendoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BAR.ctx.requestOpenBrowser();
            }
        });

        Button savedoc = new Button(BAR.ctx);
        savedoc.setBackgroundResource(R.drawable.button_save);
        savedoc.setId(R.id.two);
        savedoc.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BAR.ctx.saveDocument(false);
            }
        });

        Button savedocas = new Button(BAR.ctx);
        savedocas.setBackgroundResource(R.drawable.button_save_as);
        savedocas.setId(R.id.three);
        savedocas.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BAR.ctx.saveAsDocument(false);
            }
        });

        Button share = new Button(BAR.ctx);
        share.setBackgroundResource(R.drawable.button_share);
        share.setId(R.id.ten);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Editor editor = (Editor)BAR.ctx.getFrag();
                switch(Settings.getActionOnShare()) {
                    case Settings.AOS_FILE:
                        shareFile(editor);
                        break;
                    case Settings.AOS_CONTENT:
                        ShareHelper.shareContent(editor.getText().toString(), "text/plain", BAR.ctx);
                        break;
                    default:
                        final OptionMessage om = OptionMessage.getInstance(BAR.ctx.getString(R.string.share),
                                BAR.ctx.getString(R.string.alert_shareFileorContent), true);
                        om.show(BAR.ctx.getSupportFragmentManager(), "OptionMessage");
                        new Handler(Looper.getMainLooper()).post(new Runnable() {
                            @Override
                            public void run() {
                                om.setPositiveButton(R.string.label_share_file, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        om.dismiss();
                                        shareFile(editor);
                                    }
                                });
                                om.setNeutralButton(R.string.label_share_content, new View.OnClickListener() {
                                    @Override
                                    public void onClick(View view) {
                                        om.dismiss();
                                        ShareHelper.shareContent(editor.getText().toString(), "text/plain", BAR.ctx);
                                    }
                                });
                            }
                        });
                }
            }
        });

        Button tabs = new Button(BAR.ctx);
        tabs.setBackgroundResource(R.drawable.button_tabs);
        tabs.setId(R.id.four);
        tabs.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BAR.ctx.tabs();
            }
        });

        Button search = new Button(BAR.ctx);
        search.setBackgroundResource(R.drawable.button_search);
        search.setId(R.id.five);
        search.setOnClickListener(new View.OnClickListener() {
           @Override
           public void onClick(View view) {
               ((Editor)BAR.ctx.getFrag()).activateSearch();
           }
        });

        Button help = new Button(BAR.ctx);
        help.setBackgroundResource(R.drawable.button_help);
        help.setId(R.id.six);

        if (!twoLayer) {
            help.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HelpDialog hd = HelpDialog.newInstance(R.layout.help_editor, BAR.ctx.getString(R.string.editor));
                    hd.show(BAR.ctx.getSupportFragmentManager(), "HelpDialog");
                }
            });

            Button[] l = {settings, newdoc, opendoc, savedoc, savedocas, search, share, tabs, help};
            LAYERS = new View[1][];
            LAYERS[0] = l;
        } else {
            help.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HelpDialog hd = HelpDialog.newInstance(R.layout.help_editor_layer1, BAR.ctx.getString(R.string.editor));
                    hd.show(BAR.ctx.getSupportFragmentManager(), "HelpDialog");
                }
            });

            Button up = new Button(BAR.ctx);
            up.setBackgroundResource(R.drawable.button_arrow_up);
            up.setId(R.id.seven);
            up.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    BAR.getState().transToLayer(0);
                }
            });

            Button down = new Button(BAR.ctx);
            down.setBackgroundResource(R.drawable.button_arrow_down);
            down.setId(R.id.eight);
            down.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    BAR.getState().transToLayer(1);
                }
            });

            Button helpL2 = new Button(BAR.ctx);
            helpL2.setBackgroundResource(R.drawable.button_help);
            helpL2.setId(R.id.six);
            helpL2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    HelpDialog hd = HelpDialog.newInstance(R.layout.help_editor_layer2, BAR.ctx.getString(R.string.editor));
                    hd.show(BAR.ctx.getSupportFragmentManager(), "HelpDialog");
                }
            });

            Button[] l1 = {settings, savedoc, search, tabs, down, help};
            Button[] l2 = {newdoc, opendoc, savedocas, share, up, helpL2};
            LAYERS = new View[2][];
            LAYERS[0] = l1;
            LAYERS[1] = l2;
        }
        for (int i = 0; i < (twoLayer ? 2 : 1); i++) {
            int count = 0;
            for (View v : LAYERS[i]) {
                if (count == LAYERS[i].length - 1) {
                    v.setTranslationX(BAR.barWidth - BAR.bWidth - BAR.padding_w);
                    v.setNextFocusRightId(LAYERS[i][0].getId());
                    v.setNextFocusLeftId(LAYERS[i][count - 1].getId());
                } else {
                    v.setTranslationX(BAR.padding_w + (count * (BAR.margin + bar.bWidth)));
                    v.setNextFocusRightId(LAYERS[i][count + 1].getId());
                    if (count == 0)
                        v.setNextFocusLeftId(LAYERS[i][LAYERS[i].length - 1].getId());
                }
                v.setTranslationY(BAR.padding_h);

                v.setFocusable(true);
                v.setScaleX(1);
                v.setScaleY(1);
                v.setAlpha(1);
                ViewGroup.LayoutParams lp = new ViewGroup.LayoutParams(BAR.bar.getLayoutParams());
                lp.width = BAR.bWidth;
                lp.height = BAR.bHeight;
                v.setLayoutParams(lp);

                count++;
            }
        }
    }

    private void shareFile(final Editor editor) {
        Cursor cursor = BAR.ctx.getDB().fetchText(editor.getKey());
        if (cursor == null || cursor.getColumnIndexOrThrow(TEditDB.KEY_PATH) == -1) {
            if (cursor == null) {
                Log.e("TEdit", "Unable to share file: Database did not contain key.");
            } else {
                cursor.close();
                Log.e("TEdit", "Unable to share file: Database did not contain column");
            }
            ErrorMessage em = ErrorMessage.getInstance(BAR.ctx.getString(R.string.alert),
                    BAR.ctx.getString(R.string.error_dberror));
            em.show(BAR.ctx.getSupportFragmentManager(), "dialog");
            return;
        }

        final String path = cursor.getString(cursor.getColumnIndexOrThrow(TEditDB.KEY_PATH));
        cursor.close();
        if (path.equals(TEditActivity.DEFAULTPATH)) {
            final OptionMessage om = OptionMessage.getInstance(BAR.ctx.getString(R.string.save),
                    BAR.ctx.getString(R.string.alert_notSavedShareContent));
            om.show(BAR.ctx.getSupportFragmentManager(), "OptionMessage");
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    om.setPositiveButton(R.string.confirm, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            om.dismiss();
                            ShareHelper.shareContent(editor.getText().toString(), "text/plain", BAR.ctx);
                        }
                    });
                }
            });
            return;
        }

        final AndFile file = AndFile.createDescriptor(path, BAR.ctx);
        if (file == null || !file.exists()) {
            final OptionMessage om = OptionMessage.getInstance(BAR.ctx.getString(R.string.save),
                    BAR.ctx.getString(R.string.alert_notFoundShareContent));
            om.show(BAR.ctx.getSupportFragmentManager(), "OptionMessage");
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    om.setPositiveButton(R.string.confirm, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            om.dismiss();
                            ShareHelper.shareContent(editor.getText().toString(), "text/plain", BAR.ctx);
                        }
                    });
                }
            });
            return;
        }

        if (!editor.getSettings().saved) {
            final OptionMessage om = OptionMessage.getInstance(BAR.ctx.getString(R.string.save), BAR.ctx.getString(R.string.alert_saveShare));
            om.show(BAR.ctx.getSupportFragmentManager(), "OptionMessage");
            new Handler(Looper.getMainLooper()).post(new Runnable() {
                @Override
                public void run() {
                    om.setPositiveButton(R.string.confirm, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            om.dismiss();
                            if (file == null || !file.exists() || !file.canWrite()) {
                                //TODO
                                return;
                            }
                            BAR.ctx.saveDocument(false);

                            String error = ShareHelper.shareFile(file, file.getMIME(), BAR.ctx);
                            if (!error.isEmpty()) {
                                Log.e("TEdit Share", "TEdit was unable to share the file " + file.getPath() + ": " + error);
                                ErrorMessage em = ErrorMessage.getInstance(BAR.ctx.getString(R.string.alert),
                                        BAR.ctx.getString(R.string.error_share) + error);
                                em.show(BAR.ctx.getSupportFragmentManager(), "dialog");
                            }
                        }
                    });
                }
            });
            return;
        }

        String error = ShareHelper.shareFile(file, file.getMIME(), BAR.ctx);
        if (!error.isEmpty()) {
            Log.e("TEdit Share", "TEdit was unable to share the file " + file.getPath() + ": " + error);
            ErrorMessage em = ErrorMessage.getInstance(BAR.ctx.getString(R.string.alert),
                    BAR.ctx.getString(R.string.error_share) + error);
            em.show(BAR.ctx.getSupportFragmentManager(), "dialog");
        }
    }
}
