(function(back) {
  let settings = Object.assign({
    style : "randomcolor",
    colors : ["#00f","#0bf","#0f7","#3f0","#ff0","#f30","#f07","#b0f"]
  },require("Storage").readJSON("clockbg.json",1)||{});

  function saveSettings() {
    if (settings.style!="image")
      delete settings.fn;
    if (settings.style!="color")
      delete settings.color;
    if (!["randomcolor","squares","plasma","rings","tris","blobs","gradient"].includes(settings.style))
      delete settings.colors;
    require("Storage").writeJSON("clockbg.json", settings);
  }

function colorRange(from, to, steps) {
  var result = [];
  for (var i = 0; i < steps; i++)
    result.push(g.blendColor(from,to,i / (steps - 1)));
  return result;
}
let customMenu=function(style, col1name, col2name, bck, img) {
  var col1 = "", col2 = "";
  function buildMenu() {
    var menu = {"":{title:/*LANG*/"Custom", back:bck}};
    menu[col1name] = function() {
      require("colorpicker").show({
        back: buildMenu,
        onSelect: function(c) { col1 = c; }
      });
    };
    menu[col2name] = function() {
      require("colorpicker").show({
        back: function() { buildMenu(); },
        onSelect: function(c) { col2 = c; }
      });
    };
    if (col1 !== "" && col2 !== "") {
      menu[/*LANG*/"Save"] = function() {
        settings.style = style;
        settings.colors=[col1,col2];
        if(style=="plasma")settings.colors = colorRange(col1, col2, 16);
        if(style=="gradient")settings.image = img;
        saveSettings();
        showMainMenu();
      };
    }
    E.showMenu(menu);
  }
  buildMenu();
}

  function getColorsImage(cols) {
    var bpp = 1;
    if (cols.length>4) bpp=4;
    else if (cols.length>2) bpp=2;
    var w = (cols.length>8)?8:16;
    var b = Graphics.createArrayBuffer(w*cols.length,16,bpp);
    b.palette = new Uint16Array(1<<bpp);
    cols.forEach((c,i)=>{
      b.setColor(i).fillRect(i*w,0,i*w+w-1,15);
      b.palette[i] = g.toColor(c);
    });
    return "\0"+b.asImage("string");
  }

  function showModeMenu() {
    E.showMenu({
      "" : {title:/*LANG*/"Background", back:showMainMenu},
      /*LANG*/"Solid Color" : function() {
        require("colorpicker").show({
          back:showMainMenu,
          onSelect:function(col){
            settings.style = "color";
            settings.color = col;
            saveSettings();
          }
        })
      },
      /*LANG*/"Random Color" : function() {
        var cols = [
          ["#F00","#0F0","#FF0","#00F","#F0F","#0FF"],
          ["#F00","#0F0","#00F"],
          ["#FF0","#F0F","#0FF"],
          ["#00f","#0bf","#0f7","#3f0","#ff0","#f30","#f07","#b0f"],
          ["#66f","#6df","#6fb","#8f6","#ff6","#f86","#f6b","#d6f"],
          ["#007","#057","#073","#170","#770","#710","#703","#507"]
          // Please add some more!
        ];
        var menu =  {"":{title:/*LANG*/"Colors", back:showModeMenu},
          /*LANG*/"Custom" : () => {
          require("colorpicker").show({
            onSelect:function(colors){
              settings.style = "randomcolor";
              settings.colors = colors;
              saveSettings();
            },
            back:showMainMenu,
            multiSelect:true,
            startingSelection : settings.style=="randomcolor" ? settings.colors : []
          });
	}};
        cols.forEach(col => {
          menu[getColorsImage(col)] = () => {
            settings.style = "randomcolor";
            settings.colors = col;
            saveSettings();
            showMainMenu();
          };
        });
        E.showMenu(menu);
      },
      /*LANG*/"Image" : function() {
        let images = require("Storage").list(/clockbg\..*\.img/);
        if (images.length) {
          var menu =  {"":{title:/*LANG*/"Images", back:showModeMenu}};
          images.forEach(im => {
            menu[im.slice(8,-4)] = () => {
              settings.style = "image";
              settings.fn = im;
              saveSettings();
              showMainMenu();
            };
          });
          E.showMenu(menu);
        } else {
          E.showAlert("Please use App Loader to upload images").then(showModeMenu);
        }
      },
      /*LANG*/"Squares" : function() {
        var cols = [ // list of color palettes used as possible square colours - either 4 or 16 entries
          ["#00f","#05f","#0bf","#0fd","#0f7","#0f1","#3f0","#9f0","#ff0","#f90","#f30","#f01","#f07","#f0d","#b0f","#50f"],
          ["#44f","#48f","#4df","#4fe","#4fa","#4f6","#7f4","#bf4","#ff4","#fb4","#f74","#f46","#f4a","#f4e","#d4f","#84f"],
          ["#009","#039","#079","#098","#094","#091","#290","#590","#990","#950","#920","#901","#904","#908","#709","#309"],
          ["#0FF","#0CC","#088","#044"],
          ["#FFF","#FBB","#F66","#F44"],
          ["#fff","#bbf","#77f","#33f"],
          ["#fff","#bff","#7fe","#3fd"],
          ["#FFF","#BBB","#666","#000"]
          // Please add some more! 4 or 16 only!
        ];
        var menu =  {"":{title:/*LANG*/"Squares", back:showModeMenu},
        /*LANG*/"Random" : () => {
          settings.style = "squares";
          settings.colors = [
            ["#00f","#05f","#0bf","#0fd","#0f7","#0f1","#3f0","#9f0","#ff0","#f90","#f30","#f01","#f07","#f0d","#b0f","#50f"],
            ["#0FF","#0CC","#088","#044"],
            ["#FFF","#FBB","#F66","#F44"],
            ["#fff","#bbf","#77f","#33f"],
            ["#fff","#bff","#7fe","#3fd"]
          ];
          saveSettings();
          showMainMenu();
        }};
        cols.forEach(col => {
          menu[getColorsImage(col)] = () => {
            settings.style = "squares";
            settings.colors = col;
            saveSettings();
            showMainMenu();
          };
        });
        E.showMenu(menu);
      },
      /*LANG*/"Plasma" : function showPlasmaMenu() {
        var cols = [ // list of color palettes used as possible square colours - 16 entries
          ["#00f","#05f","#0bf","#0fd","#0f7","#0f1","#3f0","#9f0","#ff0","#f90","#f30","#f01","#f07","#f0d","#b0f","#50f"],
          ["#44f","#48f","#4df","#4fe","#4fa","#4f6","#7f4","#bf4","#ff4","#fb4","#f74","#f46","#f4a","#f4e","#d4f","#84f"],
          ["#009","#039","#079","#098","#094","#091","#290","#590","#990","#950","#920","#901","#904","#908","#709","#309"],
          ["#fff","#fef","#fdf","#fcf","#fbf","#fae","#f9e","#f8e","#f7e","#f6e","#f5d","#f4d","#f3d","#f2d","#f1d","#f0c"],
          ["#fff","#eff","#dff","#cef","#bef","#adf","#9df","#8df","#7cf","#6cf","#5bf","#4bf","#3bf","#2af","#1af","#09f"],
          ["#000","#110","#220","#330","#440","#550","#660","#770","#880","#990","#aa0","#bb0","#cc0","#dd0","#ee0","#ff0"],
          ["#000","#010","#020","#130","#140","#250","#260","#270","#380","#390","#4a0","#4b0","#5c0","#5d0","#5e0","#6f0"],
          ["#fff","#efe","#dfd","#cfc","#bfb","#afa","#9f9","#8f8","#7f7","#6f6","#5f5","#4f4","#3f3","#2f2","#1f1","#0f0"],
          ["#fff","#fee","#fdd","#fcc","#fbb","#faa","#f99","#f88","#f77","#f66","#f55","#f44","#f33","#f22","#f11","#f00"],
          // Please add some more!
        ];
        var menu =  {"":{title:/*LANG*/"Plasma", back:showModeMenu},
        /*LANG*/"Random" : () => {
          settings.style = "plasma";
          settings.colors = cols;
          saveSettings();
          showMainMenu();
        }, /*LANG*/"Custom" : () =>
          customMenu("plasma", /*LANG*/"Background",/*LANG*/"Foreground", showPlasmaMenu, undefined )
        };
        cols.forEach(col => {
          menu[getColorsImage(col)] = () => {
            settings.style = "plasma";
            settings.colors = col;
            saveSettings();
            showMainMenu();
          };
        });
        E.showMenu(menu);
      },
      /*LANG*/"Rings" : function() {
        var cols = [ // list of color palettes used as possible square colours - 2 entries
          ["#ff0","#f00"], // yellow/red
          ["#0ff","#000"], // cyan/blue
          ["#888","#000"], // grey/black
          ["#888","#fff"], // grey/white
          ["#444","#0f0"], // grey/green
          ["#444","#f0f"], // grey/purple
          ["#fff","#000"], // white/black
          ["#fff","#00f"], // white/blue
          // Please add some more!
        ];
        var menu =  {"":{title:/*LANG*/"Rings", back:showModeMenu},
        /*LANG*/"Random" : () => {
          settings.style = "rings";
          settings.colors = cols; // all colours!
          saveSettings();
          showMainMenu();
        }};
        cols.forEach(col => {
          menu[getColorsImage(col)] = () => {
            settings.style = "rings";
            settings.colors = col;
            saveSettings();
            showMainMenu();
          };
        });
        E.showMenu(menu);
      },
      /*LANG*/"Tris" : function() {
        var cols = [ // 2/4/8/16 (8/16 both use 4bpp)
          ["#00f","#05f","#0bf","#0fd","#0f7","#0f1","#3f0","#9f0","#ff0","#f90","#f30","#f01","#f07","#f0d","#b0f","#50f"],
          ["#00f","#0bf","#0f7","#3f0","#ff0","#f30","#f07","#b0f"],
          ["#0ef","#6f0","#f10","#90f"],
          ["#09f","#1f0","#f60","#e0f"],
          ["#000","#444","#888","#fff"]
          // Please add some more!
        ];
        var menu =  {"":{title:/*LANG*/"Colors", back:showModeMenu},
        /*LANG*/"Random" : () => {
          settings.style = "tris";
          settings.colors = cols; // all colours!
          saveSettings();
          showMainMenu();
        }};
        cols.forEach(col => {
          menu[getColorsImage(col)] = () => {
            settings.style = "tris";
            settings.colors = col;
            saveSettings();
            showMainMenu();
          };
        });
        E.showMenu(menu);
      },
      /*LANG*/"Blobs" : function() {
        var cols = [ // 2/4/8/16 (8/16 both use 4bpp)
          ["#fff","#f9f","#90f","#40f"],
          ["#fff","#ff0","#f00","#800"],
          ["#fff","#8ff","#08f","#00f"],
          ["#f00","#f60","#fc0","#ff0"],
          ["#0f0","#0f6","#0fc","#0ff"],
          ["#00f","#26f","#4cf","#6ff"]
          // Please add some more!
        ];
        var menu =  {"":{title:/*LANG*/"Colors", back:showModeMenu},
        /*LANG*/"Blobs" : () => {
          settings.style = "blobs";
          settings.colors = cols; // all colours!
          saveSettings();
          showMainMenu();
        }};
        cols.forEach(col => {
          menu[getColorsImage(col)] = () => {
            settings.style = "blobs";
            settings.colors = col;
            saveSettings();
            showMainMenu();
          };
        });
        E.showMenu(menu);
      },
      /*LANG*/"Gradient" : function() {
        let img="";
        let showMenu=()=>{
          var cols = [ // list of color palettes used as gradient colors
            ["#0ff","#00f"],
            ["#ff0","#0f0"],
            ["#0f0","#f00"],
            ["#0ff","#f0f"],
            ["#fff","#0ff"]
            // Please add some more!
          ];
          var menu = {"":{title:/*LANG*/"Gradient", back:showTypeMenu},
            /*LANG*/"Random" : () => {
              settings.style = "gradient";
              settings.colors = cols;
              settings.image= img;
              saveSettings();
              showMainMenu();
            }, /*LANG*/"Custom" : () =>
              customMenu("gradient", /*LANG*/"Color 1",/*LANG*/"Color 2",showMenu,img)
          };
          cols.forEach(col => {
            menu[getColorsImage(col)] = () => {
              settings.style = "gradient";
              settings.colors = col;
              settings.image= img;
              saveSettings();
              showMainMenu();
            };
          });
          E.showMenu(menu);
        };
        let showTypeMenu= () => {
          let typeMenu={
            "":{title:/*LANG*/"Select Type", back:showMainMenu},
            /*LANG*/"Vertical":function(){
              img="AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAERESISEREhEiMyMjIzMjMkRERERERERUVWZWVVVWZVZ3d2d3dnd3dpiIiYmIiIiImamqmpqqqamru7u7u7u7u8zdzN3czczM3u3e7d7t7e3///////////////////////////////8=";
              showMenu();
            },
            /*LANG*/"Horizontal":function(){
              img="//7LqHVDEAD//tqYdUIQAP/9y5h1QyAA//7LqHZDEAD//tqodUMQAP/+y6l2QyAA//7LmHZTIAD//cupdUMQAP/+y6l1QxAA//7bqHVDEAD//cuoZlIQAP/+y5h1UxAA//7bqXVDEAD//cuYdkMQAP/+y6h1QhAA//7LmHZCEAA=";
              showMenu();
            },
            /*LANG*/"Diagonal TL-BR":function(){
              img="////7cy6mYj///7dy6qYd///7cu6mYd2/+7cy6qYhmX+7dy6qYh2Ve7cy6qYh3VU7du6mYd2VFPcy6mYd2VUM8u7qIhmZUMiy7qYh2VUQyG7mYdnVEQiIKmYh2VEQyEAqYh2VUMyEQCYd3VUMyEQAJd2ZUMyEQAAd2ZUMyIAAAA=";
              showMenu();
            },
            /*LANG*/"Diagonal TR-BL":function(){
              img="d2VUQiIQAACIdlVEMhEAAJiHZVQzIQAAqZdnVUMiIQCpmYZlRDIiELuph3ZVRDIRy7qYh2ZUQyHMupmIdmVDIty7qoh3ZlRD3cy6mYh2VUTu3buqmHdlRP/tzLqph3Zl/+7dy6qZh2b//u3Lu6mHZv//7dzLupl2///+3du6qYc=";
              showMenu();
            },
            /*LANG*/"Radial":function(){
              img="AAEiMzMiEAAAEjRVVUMhAAE0Vnd3ZUMQEkV4mZmHVCEjV4mruph1MiRom83cuYZCNXms7/7Kl1M1eb3//9uXUzV5vf//25dTNXms7/7Kl1MkaJvN3LmGQiNXiau6mHUyEkV4mZmHVCEBNFZ3d2VDEAASNFVVQyEAAAEiMzMiEAA=";
              showMenu();
            }
          };
          E.showMenu(typeMenu);
        };
        showTypeMenu();
      }
    });
  }

  function showMainMenu() {
    E.showMenu({
      "" : {title:/*LANG*/"Clock Background", back:back},
      /*LANG*/"Mode" : {
        value : settings.style,
        onchange : showModeMenu
      },
      /*LANG*/"View" : () => {
        Bangle.setUI({mode:"custom",touch:showMainMenu,btn:showMainMenu});
        require("clockbg").reload();
        require("clockbg").fillRect(Bangle.appRect);
      }
    });
  }

  /* Scripts for generating colors. Change the values in HSBtoRGB to generate different effects

  a = new Array(16);
  a.fill(0);
  g.clear();
  w = Math.floor(g.getWidth()/a.length);
  print(a.map((n,i)=>{
    var j = i/(a.length-1); // 0..1
    var c = E.HSBtoRGB(j,1,1,24); // rainbow
    var c = E.HSBtoRGB(j,0.6,1,24); // faded rainbow
    var c = E.HSBtoRGB(0.8, j,1,24); // purple->white
    var c = E.HSBtoRGB(0.1, j,1,24); // blue->white
    var c = E.HSBtoRGB(0.4, 1,j,24); // black->green
    var col = c.toString(16).padStart(6,0).replace(/(.).(.).(.)./,"\"#$1$2$3\"");
    g.setColor(eval(col)).fillRect(i*w,0, i*w+w-1,31);
    return col;
  }).join(","))

  */

  showMainMenu();
})
