import copy
import fastapi
import fastapi.staticfiles as fastapiStaticfiles
import linebot
import linebot.models as linebotModels

from linebot.models import (
    MessageEvent, TextMessage, TextSendMessage,
    SourceUser, SourceGroup, SourceRoom,
    TemplateSendMessage, ConfirmTemplate, MessageAction,
    ButtonsTemplate, ImageCarouselTemplate, ImageCarouselColumn, URIAction,
    PostbackAction, DatetimePickerAction,
    CameraAction, CameraRollAction, LocationAction,
    CarouselTemplate, CarouselColumn, PostbackEvent,
    StickerMessage, StickerSendMessage, LocationMessage, LocationSendMessage,
    ImageMessage, VideoMessage, AudioMessage, FileMessage,
    UnfollowEvent, FollowEvent, JoinEvent, LeaveEvent, BeaconEvent,
    MemberJoinedEvent, MemberLeftEvent,
    FlexSendMessage, BubbleContainer, ImageComponent, BoxComponent,
    TextComponent, IconComponent, ButtonComponent, MessageTemplateAction,
    SeparatorComponent, QuickReply, QuickReplyButton,URITemplateAction,
    ImageSendMessage)

#uvicorn main:app --host 0.0.0.0 --port 443 --ssl-keyfile=/etc/letsencrypt/live/cal.ptt.cx/privkey.pem --ssl-certfile=/etc/letsencrypt/live/cal.ptt.cx/fullchain.pem
#uvicorn main:app --host 0.0.0.0 --port 443 --ssl-keyfile=/etc/letsencrypt/live/ptt.cx/privkey.pem --ssl-certfile=/etc/letsencrypt/live/ptt.cx/chain.pem

#uvicorn main:app --host 0.0.0.0 --port 443 --key-file=/etc/letsencrypt/live/ptt.cx/privkey.pem --certfile=/etc/letsencrypt/live/ptt.cx/cert.pem

# --keyfile=./key.pem --certfile=./cert.pem 

#   --ssl-cert-reqs 1 
# 
# --ssl-ca-certs=/etc/letsencrypt/live/ptt.cx/fullchain.crt

app = fastapi.FastAPI()
app.mount(
    '/static', fastapiStaticfiles.StaticFiles(directory='static'), name='static')


from linebot import (
    LineBotApi, WebhookHandler
)
from linebot.exceptions import (
    InvalidSignatureError
)
from linebot.models import (
    MessageEvent, TextMessage,ImageSendMessage, TextSendMessage,FlexSendMessage, TemplateSendMessage,CarouselTemplate,ConfirmTemplate,PostbackAction,MessageAction,CarouselColumn,URIAction
)
import json
import codecs

line_bot_api = LineBotApi('FvP2AkKj3FSuTjY8Jhwn23DPIb38yDZBliLrDjRA8j+UOQPku+kH2Bz2coDFl4gruRAiLuHuBbtRpILXlN54zJ+bWF5IwU86FClG47VZxCcDcAkhwqCqjYi/Ju7dBzlg963d9CV1KiiBwoiqvV6J7AdB04t89/1O/w1cDnyilFU=')
handler = WebhookHandler('58a73d69c3ad6416e0b465e64c30526a')
#line_bot_api = LineBotApi('YOUR_CHANNEL_ACCESS_TOKEN')
#handler = WebhookHandler('YOUR_CHANNEL_SECRET')

@app.get("/msg2/{item_id}")
async def coffee_msg2(item_id):
    line_bot_api.push_message(item_id, TextSendMessage(text='Jared 測試....開啟下方完整券樣（密碼9888）至櫃台掃碼兌換。https://txp.rs/v/EvX69b4Xq9'))
    line_bot_api.push_message(item_id, ImageSendMessage('https://cal.ptt.cx:5443/static/images/finalcoupon.png', 'https://cal.ptt.cx:5443/static/images/finalcoupon.png') )
    print('send images')
    return {"code":"ok" }


@app.get("/msg/{item_id}")
async def coffee_msg(item_id):
    line_bot_api.push_message(item_id, TextSendMessage(text='點選下方連結，輸入密碼9888，可直接至全省City Cafe (Logo)門市兌換。https://txp.rs/v/EvX69b4Xq9'))
    line_bot_api.push_message(item_id, ImageSendMessage('https://cal.ptt.cx:5443/static/images/finalcoupon.png', 'https://cal.ptt.cx:5443/static/images/finalcoupon.png') )
    print('send images')
    return {"code":"ok" }

@app.post('/callback')
async def callback(request: fastapi.Request):
    signature = request.headers['X-Line-Signature']
    body = await request.body()
    handler.handle(body.decode('utf-8'), signature)
    return 'OK'


@handler.add(FollowEvent)
def handle_follow(event):
    print("in Follow")
    print(event.source.user_id)

    button_template_message =ButtonsTemplate(
                                    thumbnail_image_url="https://cal.ptt.cx:5443/static/images/coupon.png",
                                    title='Menu', 
                                    text='填裝修問卷💖，送City Cafe 乙杯及裝修折抵券五萬元！請務必填寫真實資訊。🌻',
                                    image_size="cover",
                                    actions=[
                                        URITemplateAction(
                                        label='點我填問卷',
                                        uri='http://q.ptt.cx/a1/index-line.html?userid='+event.source.user_id
                                        ),
                                    ]
                                )
                                
    line_bot_api.reply_message(
        event.reply_token,
        TemplateSendMessage(
            alt_text="Follow Event",
            template=button_template_message
        )
    )

@handler.add(linebotModels.MessageEvent, message=linebotModels.TextMessage)
def message_text(event):
    if event.message.text == 'push':
        line_bot_api.push_message(
                event.source.user_id, [
                    TextSendMessage(text='PUSH!'),
                ]
            )
    if event.message.text == '叫':
        line_bot_api.reply_message(
            event.reply_token, linebotModels.AudioSendMessage(
                original_content_url=f'{baseUrl}/static/audio/noot_noot.mp3', duration=1000))
    if event.message.text=='ok':
        line_bot_api.reply_message(
            event.reply_token,
            TextSendMessage(text='ChoozMo 的FastAPI LINE Bot'))
    if event.message.text=='btn':
        line_bot_api.reply_message(
                    event.reply_token,
                    TextSendMessage(
                        text='Quick reply',
                        quick_reply=QuickReply(
                            items=[
                                QuickReplyButton(
                                    action=PostbackAction(label="label1", data="data1")
                                ),
                                QuickReplyButton(
                                    action=MessageAction(label="label2", text="text2")
                                ),
                                QuickReplyButton(
                                    action=DatetimePickerAction(label="label3",
                                                                data="data3",
                                                                mode="date")
                                ),
                                QuickReplyButton(
                                    action=CameraAction(label="label4")
                                ),
                                QuickReplyButton(
                                    action=CameraRollAction(label="label5")
                                ),
                                QuickReplyButton(
                                    action=LocationAction(label="label6")
                                ),
                            ])))



#if __name__ == "__main__":
#    app.run(host='0.0.0.0', port=443,ssl_context=('/etc/letsencrypt/live/ptt.cx/fullchain.pem', '/etc/letsencrypt/live/ptt.cx/privkey.pem'))
#    app.run(host='0.0.0.0', port=14404,ssl_context=('/tmp/cert.pem','/tmp/chain.pem' ))

