# Licensed to Elasticsearch B.V. under one or more contributor
# license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright
# ownership. Elasticsearch B.V. licenses this file to you 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.

import:
  - unfold_templates.yml

main: |
  package gotype

  var (
  {{/* defined 'lifted' pointer primitive unfolders into reflection based unfolders */}}
    unfolderReflIfc = liftGoUnfolder(newUnfolderIfc())
    {{ range data.primitiveTypes }}
    {{ $t := capitalize . }}
      unfolderRefl{{ $t }} = liftGoUnfolder(newUnfolder{{ $t }}())
    {{ end }}
  )

  {{/* define pointer based unfolder types */}}
  {{ invoke "makeTypeWithName" "name" "ifc" "type" "interface{}" }}
  {{ template "makeType" "bool" }}
  {{ template "makeType" "string" }}
  {{ range .numTypes }} 
    {{ template "makeType" . }}
  {{ end }}

  {{/* create value visitor callbacks */}}
  {{ invoke "onIfcFns" "name" "unfolderIfc" "fn" "assign" }}
  {{ invoke "onBoolFns" "name" "unfolderBool" "fn" "assign" }}
  {{ invoke "onStringFns" "name" "unfolderString" "fn" "assign" }}
  {{ range .numTypes }}
    {{ $type := . }}
    {{ $name := capitalize . | printf "unfolder%v" }}
    {{ invoke "onNumberFns" "name" $name "type" $type "fn" "assign" }}
  {{ end }}

  /*
  func (*unfolderIfc) OnArrayStart(ctx *unfoldCtx, l int, bt structform.BaseType) error {
    return unfoldIfcStartSubArray(ctx, l, bt)
  }

  func (u *unfolderIfc) OnChildArrayDone(ctx *unfoldCtx) error {
    v, err := unfoldIfcFinishSubArray(ctx)
    if err == nil {
      err = u.assign(ctx, v)
    }
    return err
  }
  */

# makeTypeWithName(name, type, [base])
templates.makeTypeWithName: |
  {{ $type := .type }}
  {{ $name := capitalize .name | printf "unfolder%v" }}
  {{ invoke "makeUnfoldType" "type" $type "name" $name "base" .base }}

  func (u *{{ $name }} ) initState(ctx *unfoldCtx, ptr unsafe.Pointer) {
    ctx.unfolder.push(u)
    ctx.ptr.push(ptr)
  }

  func (u *{{ $name }} ) cleanup(ctx *unfoldCtx) {
    ctx.unfolder.pop()
    ctx.ptr.pop()
  }

  func (u *{{ $name }} ) ptr(ctx *unfoldCtx) *{{ $type }} {
    return (*{{ $type }})(ctx.ptr.current)
  }

  func (u *{{ $name }}) assign(ctx *unfoldCtx, v {{ $type }}) error {
    *u.ptr(ctx) = v
    u.cleanup(ctx)
    return nil
  }
