<script lang="ts">
import { createEventDispatcher, onDestroy, onMount } from 'svelte';
import { fade } from 'svelte/transition';

import { ae, api, Element_input } from 'aether_npm_lib';
import { slct, ae_app } from './stores';

const dispatch = createEventDispatcher();

type key_val = {
    [key: string]: any;
};

let create_post_obj_promise: any;
let delete_post_obj_promise: any;
let update_post_obj_promise: any;

let disable_submit_btn = true;

if ($slct.post_id) {
    console.log(`Post ID selected: ${$slct.post_id}`);
    console.log(`Post Object selected: ${$slct.post_obj}`);

    if ($slct.post_obj) {
        // if (!$slct.post_obj.external_person_id) {
        //     $slct.post_obj['external_person_id'] = $idaa_loc.novi_uuid;
        // }
        // if (!$slct.post_obj.full_name) {
        //     $slct.post_obj['full_name'] = $idaa_loc.novi_full_name;
        // }
        // if (!$slct.post_obj.email) {
        //     $slct.post_obj['email'] = $idaa_loc.novi_email;
        // }
    }
} else {
    $slct.post_id = null;
    $slct.post_obj = {
        title: '',
        content: '',
        topic_id: null,
        anonymous: false,
        external_person_id: $idaa_loc.novi_uuid,
        full_name: $idaa_loc.novi_full_name,
        email: $idaa_loc.novi_email,

        sort: null,
        notes: null,
    };
    console.log(`Post Object started: ${$slct.post_obj}`);
}


if ($slct.post_obj) {
} else {
    console.log(`Post Object started: ${$slct.post_obj}`)
}


onMount(() => {
    console.log('** Component Mounted: ** Edit - Post Obj');

    tinymce_remove(); // This seems to fix rendering issues
    tinymce_init();
});

onDestroy(() => {
    console.log('** Component Destroyed: ** Edit - Post Obj');
    tinymce_remove(); // This seems like the right thing to do
});


function tinymce_init() {
    // REFERENCE: https://www.tiny.cloud/docs/tinymce/6/basic-setup/
    // plugins: [
    //   'advlist', 'autolink', 'link', 'image', 'lists', 'charmap', 'preview', 'anchor', 'pagebreak',
    //   'searchreplace', 'wordcount', 'visualblocks', 'visualchars', 'code', 'fullscreen', 'insertdatetime',
    //   'media', 'table', 'emoticons', 'template', 'help'
    // ],
    // 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent'

    // NOTE: Basic version of the TinyMCE editor
    tinymce.init({
        selector: '.tinymce_editor.editor_basic',
        // width: 600,
        height: 400,
        plugins: [ 'lists', 'code', 'help' ],
        menubar: false,
        toolbar: 'undo redo | styles | bold italic | alignleft aligncenter | bullist numlist outdent indent | code | help',
        });

    // NOTE: Minimal version of the TinyMCE editor
    tinymce.init({
        selector: '.tinymce_editor.editor_basic_200',
        // width: 600,
        height: 200,
        plugins: [ 'lists', 'code', 'help' ],
        menubar: false,
        toolbar: 'undo redo | styles | bold italic | alignleft aligncenter | bullist numlist outdent indent | code | help',
        });

    // NOTE: Less is more version of the TinyMCE editor
    tinymce.init({
        selector: '.tinymce_editor.editor_less_100',
        // width: 600,
        height: 100,
        // plugins: [ 'lists', 'code', 'help' ],
        menubar: false,
        toolbar: false,
        statusbar: false,
        });

}

function tinymce_remove() {
    tinymce.remove('.tinymce_editor.editor_basic');
    tinymce.remove('.tinymce_editor.editor_basic_200');
    tinymce.remove('.tinymce_editor.editor_less_100');
}


// let ae_iframe_height = window.outerHeight;
let ae_iframe_height = window.innerHeight;
console.log(`ae_iframe_height: ${ae_iframe_height}`);
$: if (ae_iframe_height) {
    console.log('ae_iframe_height changed:', ae_iframe_height);

    let iframe_height = ae_iframe_height; // TESTING!!!

    // window.parent.postMessage({'iframe_height': `${iframe_height}px`}, "*");
    window.parent.postMessage({'iframe_height': iframe_height}, "*");
}


$: if ($slct.post_obj) {
    console.log('Selected post object changed?');
    console.log($slct.post_obj);

    if ($slct.post_obj == null) {
        $slct.post_obj = {title: null, content: null, name: null, description: null, notes: null, created_on: null, updated_on: null};
    } else {
        disable_submit_btn = false;
    }

    // ae.input_template['event']['timezone'] = 'EDT';
}


async function handle_submit_form(event) {
    console.log('*** handle_submit_form() ***');
    // console.log(event.target);

    disable_submit_btn = true;

    let form_data = new FormData(event.target);
    // console.log(form_data);

     // Form Post object data incoming
    let post_di = ae.util.extract_prefixed_form_data({prefix: null, form_data: form_data, trim_values: true, bool_tf_str: true, log_lvl: 1});
    // console.log(post_di);

    // Form Post object data outgoing
    let post_do: key_val = {};

    if (!$slct.post_id) {
        post_do['account_id_random'] = $ae_app.account_id;
        post_do['enable'] = true;
    }

    post_do['title'] = post_di.title;

    if (tinyMCE.get('content')) {
        post_do['content'] = tinyMCE.get('content').getContent();
    } else {
        post_do['content'] = post_di.content;
    }
    if (!post_do['content']) {
        console.log('The content is required.');
        disable_submit_btn = false;
        alert('The text for the post is required.');
        return false;
    }

    if (post_di.topic_id) {
        post_do['topic_id'] = Number(post_di.topic_id);
        // post_do['topic_id'] = post_di.topic_id;
    } else {
        post_do['topic_id'] = null;
    }

    console.log(post_di.anonymous);
    console.log(typeof post_di.anonymous);

    // console.log(Boolean(post_di.anonymous));
    // console.log(Number((post_di.anonymous)));
    // console.log(Boolean(Number((post_di.anonymous))));
    // let anonymous_test = Boolean(post_di.anonymous)

    // console.log(!anonymous_test);
    // console.log(!!anonymous_test);
    // console.log(!!!anonymous_test);

    post_do['anonymous'] = post_di.anonymous;

    post_do['external_person_id'] = post_di.external_person_id;
    post_do['full_name'] = post_di.full_name;
    post_do['email'] = post_di.email;

    post_do['hide'] = !!post_di.hide;
    post_do['priority'] = !!post_di.priority;
    if (post_di.sort) {
        post_do['sort'] = Number(post_di.sort);
    } else {
        post_do['sort'] = null;
    }
    if (post_di.group) {
        post_do['group'] = post_di.group;
    } else {
        post_do['group'] = null;
    }

    if (post_di.enable) {
        post_do['enable'] = !!post_di.enable;
    }

    if (tinyMCE.get('notes')) {
        post_do['notes'] = tinyMCE.get('notes').getContent();
    } else {
        post_do['notes'] = post_di.notes;
    }

    console.log(post_do);

    if (!$slct.post_id) {
        create_post_obj_promise = api.create_ae_obj_crud({
            api_cfg: $ae_app.ae_api,
            obj_type: 'post',
            fields: post_do,
            key: $ae_app.ae_api.api_crud_super_key,
            log_lvl: 1
            })
        .then(function (post_obj_create_result) {
            if (!post_obj_create_result) {
                console.log('The result was null or false.');
                return false;
            }

            $slct.post_id = post_obj_create_result.obj_id_random;

            dispatch(
                'created__post_obj',
                {
                    post_id: $slct.post_id,
                }
            );

            return post_obj_create_result;
        })
        .catch(function (error) {
            console.log('Something went wrong.');
            console.log(error);
            return false;
        });

        return create_post_obj_promise;

    } else {
        update_post_obj_promise = api.update_ae_obj_id_crud({
            api_cfg: $ae_app.ae_api,
            obj_type: 'post',
            obj_id: $slct.post_id,
            fields: post_do,
            key: $ae_app.ae_api.api_crud_super_key,
            log_lvl: 1
            })
        .then(function (post_obj_update_result) {
            if (!post_obj_update_result) {
                console.log('The result was null or false.');
                return false;
            }

            dispatch(
                'updated__post_obj',
                {
                    post_id: $slct.post_id,
                }
            );

            return post_obj_update_result;
        })
        .catch(function (error) {
            console.log('Something went wrong.');
            console.log(error);
            return false;
        });

        return update_post_obj_promise;
    }
}


async function handle_delete_post_obj({post_id, method='disable'}) {
    console.log('*** handle_delete_post_obj() ***');

    delete_post_obj_promise = api.delete_ae_obj_id_crud({
        api_cfg: $ae_app.ae_api,
        obj_type: 'post',
        obj_id: post_id,
        method: method,
        // params: params,
        key: $ae_app.ae_api.api_crud_super_key,
        log_lvl: 0
        })
    .then(function (post_obj_delete_result) {
        if (post_obj_delete_result) {
            // console.log(`Result:`, post_obj_delete_result);

            dispatch(
                'deleted__post_obj',
                {
                    post_id: post_id,
                }
            );
        }
    })
    .catch(function (error) {
        console.log('The result was null or false when trying to delete.', error);
    });

    return delete_post_obj_promise;
}
</script>


<section
    class="svelte_component ae_edit post_obj"
    class:ae_create={!$slct.post_id}
    bind:clientHeight={$ae_app.iframe_height_modal_body}
    >

<form on:submit|preventDefault={handle_submit_form} class="">

    {#await update_post_obj_promise}
        <div class="awaiting alert_msg_pulse" out:fade={{ duration: 2000 }}>Saving...</div>
    {:then}
        {#if update_post_obj_promise}
            <div class="awaiting" out:fade={{ duration: 2000 }}>Finished saving</div>
        {:else}
            <!-- <div class="awaiting" out:fade={{ duration: 2000 }}>Nothing here yet</div> -->
        {/if}
    {/await}

    <h3>Post</h3>

    <label for="title">Title of BB post
        <input type="text" id="title" name="title" class="ae_width_lg" required max="200" value={$slct.post_obj.title ? $slct.post_obj.title : '' } placeholder="The title of the BB post">
    </label>

    <label class="ae_label post__content" for="content">Content (post body)
        <textarea id="content" name="content" rows="6" cols="70" bind:value={$slct.post_obj.content} class="ae_value post__content tinymce_editor editor_basic_200" placeholder="The text of the Bulletin Board post"></textarea>
    </label>

    <label for="topic_id">BB post topic
    <select id="topic_id" name="topic_id" value={$slct.post_obj.topic_id}>
        <option value="">-- None --</option>
        <option value={16}>Licensing/ monitoring/ credentialing issues</option>
        <option value={17}>Return to practice</option>
        <option value={18}>Contacts/ sponsorship in my area</option>
        <option value={19}>Professional positions</option>
        <option value={21}
            disabled={!$ae_loc.trusted_access}
            >
            Announcement
        </option>
    </select>
    </label>

    <h3>Poster's Information</h3>
    <fieldset class="">
        <legend class="">Post as Anonymous</legend>
        <div class="">
            <input
                type="radio"
                id="anonymous_no"
                name="anonymous"
                value={false}
                bind:group={$slct.post_obj.anonymous}

                >
            <label for="anonymous_no">No, include my name and email address</label>
        </div>
        <div class="">
            <input
                type="radio"
                id="anonymous_yes"
                name="anonymous"
                value={true}
                bind:group={$slct.post_obj.anonymous}

                >
            <label for="anonymous_yes">Yes, the post will be listed as Anonymous</label>
        </div>
    </fieldset>

    <label for="external_person_id"><span class="fas fa-link"></span> Linked with Novi ID
        {#if !$ae_loc.trusted_access}
            <span class="fas fa-lock" title="Field is locked"></span>
            <input
                type="text"
                id="external_person_id"
                name="external_person_id"
                value={($slct.post_obj.external_person_id ? $slct.post_obj.external_person_id : $idaa_loc.novi_uuid)}
                readonly={true}
                class="ae_width_lg"
                >
        {:else}
            <div class="ae_highlight">Primary link using the Novi API UUID. This must be empty, a staff person, or an active member of IDAA and should be the primary contact for this meeting.</div>
            <span class="fas fa-unlock" title="Field is unlocked"></span>
            <input
                type="text"
                id="external_person_id"
                name="external_person_id"
                value={($slct.post_obj.external_person_id ? $slct.post_obj.external_person_id : '')}
                readonly={false}
                class="ae_width_lg"
                >
        {/if}
    </label>

    <label for="full_name">Name
        {#if !$ae_loc.trusted_access}
            <span class="fas fa-lock" title="Field is locked"></span>
        {:else}
            <span class="fas fa-unlock" title="Field is unlocked"></span>
        {/if}
        <input
            type="text"
            id="full_name"
            name="full_name"
            value={($slct.post_obj.full_name ? $slct.post_obj.full_name : $idaa_loc.novi_full_name)}
            readonly={!$ae_loc.trusted_access}
            >
    </label>

    {#if $ae_loc.trusted_access}
    <label for="email">Email
        {#if !$ae_loc.trusted_access}
            <span class="fas fa-lock" title="Field is locked"></span>
        {:else}
            <span class="fas fa-unlock" title="Field is unlocked"></span>
        {/if}
        <input
            type="text"
            name="email"
            value={($slct.post_obj.email ? $slct.post_obj.email : $idaa_loc.novi_email)}
            readonly={!$ae_loc.trusted_access}
            >
        <span class="ae_highlight">Secondary link using the Novi email address</span>
    </label>
    {/if}

    <!-- <h3>Poster's Options</h3> -->

    <!-- <fieldset class="">
        <legend class="">Official or Member Post</legend>
        <div class="">
            <input type="radio" class="" id="group_official" name="group" value="official">
            <label for="group_official" class="">Post as Official/Leadership</label>
        </div>
        <div class="">
            <input type="radio" class="" id="group_member" name="group" value="member" checked="">
            <label for="group_member" class="">Post as Member</label>
        </div>
    </fieldset> -->

    <!-- <fieldset class="">
        <legend class="">Enable Comments</legend>
        <div class="">
            <input type="radio" class="" id="enable_comments_no" name="enable_comments" value="0">
            <label for="enable_comments_no" class="">No, do not allow comments</label>
        </div>
        <div class="">
            <input type="radio" class="" id="enable_comments_yes" name="enable_comments" value="1" checked>
            <label for="enable_comments_yes" class="">Yes, allow comments</label>
        </div>
    </fieldset> -->


    {#if $ae_loc.trusted_access}
    <section class="ae_section post__admin_options"> <!-- BEGIN: section post__admin_options -->

        <h3>
            Admin Options
            <button type="button" class="ae_btn ae_d_none_toggle ae_float_right ae_smallest btn btn-xs btn-info" on:click={() => {document.querySelector('.ae_d_none_content').classList.toggle('ae_fade_out'); document.querySelector('.ae_d_none_content').classList.toggle('ae_fade_in');}}><span class="fas fa-eye"></span> Show/Hide Admin</button>
        </h3>

        <span class="ae_d_none_content ae_fade_out">
        <label>Hide
            <input
                type="checkbox"
                name="hide"
                id="hide"
                bind:checked={$slct.post_obj.hide}
                >
        </label>

        <label>Priority
            <input
                type="checkbox"
                name="priority"
                id="priority"
                bind:checked={$slct.post_obj.priority}
                >
        </label>

        <label>Sort <input type="number" name="sort" value={$slct.post_obj.sort} /></label>

        <label>Group <input type="text" name="group" value={$slct.post_obj.group ? $slct.post_obj.group : ''} max="100" /></label>

        {#if $ae_loc.administrator_access}
        <label>Enable
            <input
                type="checkbox"
                name="enable"
                id="enable"
                bind:checked={$slct.post_obj.enable}
                >
        </label>
        {/if}

        {#if $ae_loc.trusted_access}
        <label>Internal Staff Notes
        <textarea id="notes" name="notes" class="ae_value post__notes" rows="2" cols="70" value={$slct.post_obj.notes}></textarea>
        </label>
        {/if}

        </span> <!-- END: span ae_show_hide_content -->

    </section> <!-- END: section post__admin_options -->
    {/if}


    <section class="ae_section ae_options ae_row">
        <button type="submit" class="ae_btn btn btn-primary"><span class="fas fa-check"></span> Save Post</button>

        {#if $slct.post_id}
        {#if $ae_loc.administrator_access}
        <button
            on:click={() => {
                if (!confirm('Are you sure you want to delete this post?')) {return false;}
                handle_delete_post_obj({post_id: $slct.post_id, method: 'delete'});

                $slct.post_id = null;
                $slct.post_obj = {};
            }}
            class="ae_btn ae_smallest btn btn-danger" type="button"
            title="Delete record permanently"
            >
            <span class="fas fa-minus"></span> Delete
        </button>
        {:else if $ae_loc.trusted_access}
        <button
            on:click={() => {
                if (!confirm('Are you sure you want to disable this post?')) {return false;}
                handle_delete_post_obj({post_id: $slct.post_id, method: 'disable'});

                $slct.post_id = null;
                $slct.post_obj = {};
            }}
            class="ae_btn ae_smallest btn btn-danger" type="button"
            title="Disable record to delete"
            >
            <span class="fas fa-minus"></span> Disable
        </button>
        {:else}
        <button
            on:click={() => {
                if (!confirm('Are you sure you want to hide this post?')) {return false;}
                handle_delete_post_obj({post_id: $slct.post_id, method: 'hide'});

                $slct.post_id = null;
                $slct.post_obj = {};
            }}
            class="ae_btn ae_smallest btn btn-danger" type="button"
            title="Hide record to delete"
            >
            <span class="fas fa-comment-slash"></span> Delete
        </button>
        {/if}
        {/if}
    </section>

</form>

</section>


<style>
</style>
