/*
 *  Copyright 2014 Embedded Artists AB
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */


#include "mbed.h"
#include "EthernetInterface.h"
#include "AppDraw.h"
#include "lpc_swim_font.h"
#include "lpc_colors.h"

/******************************************************************************
 * Defines and typedefs
 *****************************************************************************/
 
#define BTN_OFF    20

/******************************************************************************
 * Local variables
 *****************************************************************************/

static const COLOR_T COLORS[] = {
  RED,
  GREEN,
  BLUE,
  CYAN,
  MAGENTA,
  YELLOW,
  BLACK,
};

/******************************************************************************
 * Private functions
 *****************************************************************************/

static void buttonClicked(uint32_t x)
{
  bool* done = (bool*)x;
  *done = true;
}

void AppDraw::draw()
{
    // Prepare fullscreen
    swim_window_open(_win, 
                   _disp->width(), _disp->height(),         // full size
                   (COLOR_T*)_fb,
                   0,0,_disp->width()-1, _disp->height()-1, // window position and size
                   0,                                       // border
                   WHITE, WHITE, BLACK);                    // colors: pen, backgr, forgr
    
    _btn = new ImageButton(_win->fb, _win->xpmax - BTN_OFF - _resOk->width(), _win->ypmax - BTN_OFF - _resOk->height(), _resOk->width(), _resOk->height());
    _btn->loadImages(_resOk);
    _btn->draw();
}

/******************************************************************************
 * Public functions
 *****************************************************************************/

AppDraw::AppDraw() : _disp(NULL), _win(NULL), _fb(NULL), _btn(NULL), _resOk(NULL)
{
}

AppDraw::~AppDraw()
{
    teardown();
}

bool AppDraw::setup()
{
    _disp = DMBoard::instance().display();
    _win = (SWIM_WINDOW_T*)malloc(sizeof(SWIM_WINDOW_T));
    _fb = _disp->allocateFramebuffer();

    return (_win != NULL && _fb != NULL);
}

void AppDraw::runToCompletion()
{
    // Alternative 1: use the calling thread's context to run in
    bool done = false;
    draw();
    _btn->setAction(buttonClicked, (uint32_t)&done);
    void* oldFB = _disp->swapFramebuffer(_fb);
    
    // Wait for touches
    TouchPanel* touch = DMBoard::instance().touchPanel();
    bool ignore;
    int fingers = 0;
    touch->info(&ignore, &fingers, &ignore);
    if (fingers > MaxSupportedFingers) {
        fingers = MaxSupportedFingers;
    }
    while(!done) {
      // wait for a new touch signal (signal is sent from AppLauncher,
      // which listens for touch events)
      Thread::signal_wait(0x1);
      if (touch->read(_coords, fingers) == TouchPanel::TouchError_Ok) {
        for (int i = 0; i < fingers; i++) {
          if (_coords[i].z > 0) {
            _win->pen = COLORS[i];
            swim_put_circle(_win, _coords[i].x, _coords[i].y, 2, 1);
          }
        }
        if (_btn->handle(_coords[0].x, _coords[0].y, _coords[0].z > 0)) {
            _btn->draw();
        }
      }
    }
    
    // User has clicked the button, restore the original FB
    _disp->swapFramebuffer(oldFB);
    swim_window_close(_win);
}

bool AppDraw::teardown()
{
    if (_win != NULL) {
        free(_win);
        _win = NULL;
    }
    if (_fb != NULL) {
        free(_fb);
        _fb = NULL;
    }
    if (_btn != NULL) {
        delete _btn;
        _btn = NULL;
    }
    return true;
}


void AppDraw::addResource(Resources id, Resource* res)
{
    _resOk = res;
}

